diff --git a/R/glue.R b/R/glue.R index 3cc96688b..76f3914b6 100644 --- a/R/glue.R +++ b/R/glue.R @@ -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. @@ -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")) { diff --git a/R/inline.R b/R/inline.R index 3152bfb72..2a28eb2d3 100644 --- a/R/inline.R +++ b/R/inline.R @@ -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" diff --git a/tests/testthat/test-collapsing.R b/tests/testthat/test-collapsing.R index 2a567cc5c..67ee579e7 100644 --- a/tests/testthat/test-collapsing.R +++ b/tests/testthat/test-collapsing.R @@ -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(