ansi_substr: Substring of an ANSI-styled string, keeping correct colors

Description Usage Arguments Value Examples

View source: R/substring.R

Description

These functions are the ANSI-aware counterparts of base::substr() and base::substring(). They extract substrings from a character vector, while keeping the colors and style of the characters in the strings the same.

Usage

1
2
3
ansi_substr(x, start, stop)

ansi_substring(text, first, last = 1000000L)

Arguments

x, text

A character vector.

start, first

Integer, the first element to be extracted.

stop, last

Integer, the last element to extracted.

Value

For substr, a character vector of the same length and with the same attributes as x (after possible coercion).

For substring, a character vector of length the longest of the arguments. This will have names taken from x (if it has any after coercion, repeated as needed), and other attributes copied from x if it is the longest of the arguments).

Examples

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
str <- crayon::bold(
  "This text is bold, and", crayon::red("parts of it are red,"),
  "parts of it not."
)
cat(str, "\n")

cat(ansi_substr(str, 1, 17), "\n")
cat(ansi_substr(str, 1, 42), "\n")
cat(ansi_substr(str, 24, 42), "\n")

## Vector arguments, just like in base::substring and base::substr
cat(ansi_substr(c(str, str), c(1, 20), c(22, 42)), sep = "\n")
cat(ansi_substring(str, 1:30, 1:30), "\n")

r-lib/ansistrings documentation built on March 7, 2020, 10:13 p.m.