Skip to content

Commit

Permalink
Use vec-last for length-2 vecs if no vec-sep2
Browse files Browse the repository at this point in the history
Another fix for #681.
  • Loading branch information
gaborcsardi committed Aug 28, 2024
1 parent 53b1c8a commit a8698f2
Show file tree
Hide file tree
Showing 3 changed files with 11 additions and 6 deletions.
5 changes: 3 additions & 2 deletions R/glue.R
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,8 @@ drop_null <- function(x) {
#' to collapse.
#' @param sep Separator. A character string.
#' @param sep2 Separator for the special case that `x` contains only two
#' elements. A character string.
#' elements. A character string. Defaults to the value of `last` without the
#' serial comma.
#' @param last Last separator, if there is no truncation. E.g. use
#' `", and "` for the [serial
#' comma](https://en.wikipedia.org/wiki/Serial_comma). A character string.
Expand Down Expand Up @@ -112,7 +113,7 @@ drop_null <- function(x) {
#' # head style
#' ansi_collapse(letters, trunc = 5, style = "head")

ansi_collapse <- function(x, sep = ", ", sep2 = " and ", last = ", and ",
ansi_collapse <- function(x, sep = ", ", sep2 = sub("^,", "", last), last = ", and ",
trunc = Inf, width = Inf, ellipsis = symbol$ellipsis,
style = c("both-ends", "head")) {

Expand Down
4 changes: 2 additions & 2 deletions R/inline.R
Original file line number Diff line number Diff line change
Expand Up @@ -43,9 +43,9 @@ inline_generic <- function(app, x, style) {
}

inline_collapse <- function(x, style = list()) {
sep <- style[["vec-sep"]] %||% style[["vec_sep"]] %||% ", "
sep2 <- style[["vec-sep2"]] %||% style[["vec_sep2"]] %||% " and "
last <- style[["vec-last"]] %||% style[["vec_last"]] %||% ", and "
sep <- style[["vec-sep"]] %||% style[["vec_sep"]] %||% ", "
sep2 <- style[["vec-sep2"]] %||% style[["vec_sep2"]] %||% sub("^,", "", last)

trunc <- style[["vec-trunc"]] %||% style[["vec_trunc"]] %||% 20L
col_style <- style[["vec-trunc-style"]] %||% "both-ends"
Expand Down
8 changes: 6 additions & 2 deletions tests/testthat/test-collapsing.R
Original file line number Diff line number Diff line change
Expand Up @@ -200,9 +200,13 @@ test_that("ansi_collapse uses `sep2` for length-two inputs", {


test_that("Issue #681", {
expect_equal(ansi_collapse(1:2, last = " or "), "1 or 2")
expect_equal(ansi_collapse(1:2, sep2 = " and ", last = " or "), "1 or 2")
# sep2 takes precedence
expect_equal(ansi_collapse(1:2, sep2 = " and ", last = " or "), "1 and 2")
expect_equal(ansi_collapse(1:2, sep2 = " xor ", last = " or "), "1 xor 2")
# default for sep2 is last without the Oxford comma
expect_equal(ansi_collapse(1:3, last = ", or "), "1, 2, or 3")
expect_equal(ansi_collapse(1:2, last = ", or "), "1 or 2")
expect_equal(ansi_collapse(1:2, last = " or "), "1 or 2")

expect_snapshot({
v <- cli::cli_vec(
Expand Down

0 comments on commit a8698f2

Please sign in to comment.