ansi_substr: Substring(s) of an ANSI colored string

View source: R/ansiex.R

ansi_substrR Documentation

Substring(s) of an ANSI colored string

Description

This is a color-aware counterpart of base::substr(). It works exactly like the original, but keeps the colors in the substrings. The ANSI escape sequences are ignored when calculating the positions within the string.

Usage

ansi_substr(x, start, stop)

Arguments

x

Character vector, potentially ANSI styled, or a vector to coerced to character.

start

Starting index or indices, recycled to match the length of x.

stop

Ending index or indices, recycled to match the length of x.

Value

Character vector of the same length as x, containing the requested substrings. ANSI styles are retained.

See Also

Other ANSI string operations: ansi_align(), ansi_columns(), ansi_nchar(), ansi_strsplit(), ansi_strtrim(), ansi_strwrap(), ansi_substring(), ansi_toupper(), ansi_trimws()

Examples

str <- paste(
  col_red("red"),
  "default",
  col_green("green")
)

cat(str, "\n")
cat(ansi_substr(str, 1, 5), "\n")
cat(ansi_substr(str, 1, 15), "\n")
cat(ansi_substr(str, 3, 7), "\n")

substr(ansi_strip(str), 1, 5)
substr(ansi_strip(str), 1, 15)
substr(ansi_strip(str), 3, 7)

str2 <- paste(
  "another",
  col_red("multi-", style_underline("style")),
  "text"
)

cat(str2, "\n")
cat(ansi_substr(c(str, str2), c(3,5), c(7, 18)), sep = "\n")
substr(ansi_strip(c(str, str2)), c(3,5), c(7, 18))

cli documentation built on June 22, 2024, 10:57 a.m.