Counterparts to R string manipulation functions that account for the effects of ANSI text formatting control sequences.
Many terminals will recognize special sequences of characters in strings and change display behavior as a result. For example, on my terminal the sequence
"\033[42m" turns text background green:
The sequence itself is not shown, but the text display changes.
This type of sequence is called an ANSI CSI SGR control sequence. Most *nix terminals support them, and newer versions of Windows and Rstudio consoles do too. You can check whether your display supports them by running
fansi functions behave as expected depends on many factors, including how your particular display handles Control Sequences. See
?fansi for details, particularly if you are getting unexpected results.
ANSI control characters and sequences (Control Sequences hereafter) break the relationship between byte/character position in a string and display position.
For example, in
"Hello \033[42mWorld, Good\033[m Night Moon!" the space after “World,” is thirteenth displayed character, but the eighteenth actual character (“33” is a single character, the ESC). If we try to split the string after the space with
substr things go wrong in several ways:
We end up cutting up our string in the middle of “World”, and worse the formatting bleeds out of our string into the prompt line. Compare to what happens when we use
substr_ctl, the Control Sequence aware version of
fansi provides counterparts to the following string functions:
These are drop-in replacements that behave (almost) identically to the base counterparts, except for the Control Sequence awareness.
fansi also includes improved versions of some of those functions, such as
substr2_ctl which allows for width based substrings. There are also utility functions such as
strip_ctl to remove Control Sequences and
has_ctl to detect whether strings contain them.
fansi is written in C so you should find performance of the
fansi functions to be comparable to the base functions.
strwrap_ctl is much faster, and
strsplit_ctl is somewhat slower than the corresponding base functions.
You can translate ANSI CSI SGR formatted strings into their HTML counterparts with
This package is available on CRAN:
It has no dependencies.
For the development version use:
fansi.dl <- tempfile() fansi.uz <- tempfile() download.file('https://github.com/brodieG/fansi/archive/master.zip', fansi.dl) unzip(fansi.dl, exdir=fansi.uz) install.packages(file.path(fansi.uz, 'fansi-master'), repos=NULL, type='source') unlink(c(fansi.dl, fansi.uz))