| 1 |
#' Calculate display width |
| 2 |
#' |
| 3 |
#' `get_extent()` calculates the display width for each string in a character |
| 4 |
#' vector. |
| 5 |
#' |
| 6 |
#' @param x A character vector. |
| 7 |
#' @export |
| 8 |
#' @importFrom cli ansi_strip |
| 9 |
#' @importFrom cli utf8_nchar |
| 10 |
#' @examples |
| 11 |
#' get_extent(c("abc", "de")) |
| 12 |
#' get_extent("\u904b\u6c23") |
| 13 |
get_extent <- function(x) { |
| 14 |
force(x) |
| 15 |
x <- ansi_strip(x) |
| 16 |
width <- utf8_nchar(x, "width") |
| 17 |
if (anyNA(width)) { |
| 18 |
is_na <- which(is.na(width)) |
| 19 |
width[is_na] <- nchar(x[is_na], type = "width") |
| 20 |
} |
| 21 |
width |
| 22 |
} |
| 23 |
|
| 24 |
#' @description |
| 25 |
#' `get_max_extent()` calculates the maximum display width of all strings in a |
| 26 |
#' character vector, zero for empty vectors. |
| 27 |
#' @export |
| 28 |
#' @rdname get_extent |
| 29 |
#' @examples |
| 30 |
#' get_max_extent(c("abc", "de")) |
| 31 |
get_max_extent <- function(x) { |
| 32 |
max(get_extent(x), 0L, na.rm = TRUE) |
| 33 |
} |
| 34 |
|
| 35 |
#' Alignment helper |
| 36 |
#' |
| 37 |
#' Facilitates easy alignment of strings within a character vector. Designed to |
| 38 |
#' help implementers of formatters for custom data types. |
| 39 |
#' |
| 40 |
#' @param x A character vector |
| 41 |
#' @param width The width that each string is padded to. If `NULL`, the maximum |
| 42 |
#' display width of the character vector is used (see [get_max_extent()]). |
| 43 |
#' @param align How should strings be aligned? If `align = left` then padding |
| 44 |
#' appears on the `right`, and vice versa. |
| 45 |
#' @param space What character should be used for the padding? |
| 46 |
#' @export |
| 47 |
#' @examples |
| 48 |
#' align(c("abc", "de"), align = "left") |
| 49 |
#' align(c("abc", "de"), align = "right") |
| 50 |
align <- function(x, width = NULL, align = c("left", "right"), space = " ") { |
| 51 |
"!!!!!DEBUG align(`v(x)`, `v(class(x))`)" |
| 52 |
|
| 53 |
align <- match.arg(align) |
| 54 |
extent <- get_extent(x) |
| 55 |
if (is.null(width)) { |
| 56 |
width <- max(extent) |
| 57 |
} |
| 58 |
align_impl(x, width, align, space, extent) |
| 59 |
} |
| 60 |
|
| 61 |
align_impl <- function(x, width, align, space, extent) { |
| 62 |
spaces <- pmax(width - extent, 0L) |
| 63 |
if (align == "left") { |
| 64 |
paste0(x, strrep(space, spaces)) |
| 65 |
} else { |
| 66 |
paste0(strrep(space, spaces), x) |
| 67 |
} |
| 68 |
} |