Wrap text at blank characters to achieve a maximum line width.
Arguments
- x
character vector to be wrapped.
- width
natural number giving the maximum line width (in characters) after wrapping. Can be
Infto not wrap text.- ignore_newlines
TRUEorFALSE: should newlines inxbe replaced by blank characters?- warn_length
TRUEorFALSE: warn if a fragment exceedswidth?
Value
A character string containing x wrapped to a
maximum of width characters, with newlines inserted at blank characters. A
warning is issued if warn_length is TRUE and the width of a fragment in
the output exceeds width: this occurs if a stretch of characters longer
than width occurs without a blank character to wrap at.
Details
character(0) input to x is returned unchanged, with a warning.
x of length larger than one is pasted into a single string, separating the
parts by blank characters.
Consecutive white space is collapsed into a single blank character, except
for double spaces after periods, question marks and exclamation marks (as
documented in the section Details of strwrap()).
Leading and trailing newlines are collapsed into a single blank character if
ignore_newlines is TRUE and are retained if ignore_newlines is FALSE.
Programming notes
The call wrap_text(x, width) can be replaced by
paste0(strwrap(x, width + 1L), collapse = "\n") if x has length one and
ignore_newlines is TRUE.
Using wrap_text() on x of variable length, e.g., in the text of warnings
that report a file path or a user-provided variable name, makes the location
of newlines unpredictable and thus difficult to test reliably. To circumvent
this, put the constant part in the front of the message and hardcode newlines
using \n.
Notes
The output is printed as a string with newlines represented as \n. Use
cat() on the output to print it in the way it is formatted in messages.
Argument width in wrap_text() indicates the maximum width of text after
wrapping, i.e., the width after which text should be wrapped. In
contrast, argument width in strwrap() indicates the width at which
text should be wrapped.
See also
Other functions to modify character vectors:
as.numeric_safe(),
reexports,
replace_vals(),
signal_text(),
unpaste_unquote(),
vect_to_char()
Examples
example_text <- "A piece\nof text that you want to wrap over multiple lines"
cat(wrap_text(example_text,
width = 20, ignore_newlines = TRUE))
#> A piece of text that
#> you want to wrap
#> over multiple lines
cat(wrap_text(example_text,
width = 20, ignore_newlines = FALSE))
#> A piece
#> of text that you
#> want to wrap over
#> multiple lines