uw: 'Unwrap' strings by ignoring hard-wrapping from the source...

View source: R/string_tools.R

uwR Documentation

'Unwrap' strings by ignoring hard-wrapping from the source code

Description

It is often necessary to break a very long string (e.g. a figure caption) across several lines in your source code to keep it readable. In base R, you do this by breaking the caption into several substrings and paste()ing them together, which is kind of clumsy. This function lets you write a single string that is visually hard-wrapped with newlines and spaces, but removes those whitespace characters from the final output.

Usage

uw(..., collapse = " ", join = " ")

uw0(...)

Arguments

...

(Character) Vectors that you want to collapse into a single string. They will be coerced to Character.

collapse

(Character) All of the elements in ... will be joined together, with collapse as the separator between them.

join

(Character) Separate lines will be joined with this string.

Details

uw() will take any linebreak that is followed by any number of spaces and replace it with a single space (or whatever string you specify in the join argument). This means that if you want to insert a linebreak ⁠\\n⁠ manually, then it should not have any spaces after it. A ⁠\\n⁠ that is at the very end of a line will be kept.

If you want to unwrap without adding spaces at all, use uw0(), which is a shortcut for uw(..., collapse = "", join = "").

Also note that since uw() uses the presence of indenting spaces to decide whether a piece of text is hard-wrapped, text that merely goes to the 0th column is not unwrapped. Compare:

text <- "This will be
        unwrapped by uw()."

text <- "This will NOT
be unwrapped by uw()."

Value

A string with all elements in ... joined together and separated with collapse. Linebreaks that are not immediately followed by one or more spaces will be kept.

Authors

Examples

text <- "Here's some
         multi-line text.\n
         This is on a new line."

print(text)

#> [1] "Here's some\n         multi-line text.\n\n         This is on a new line."

cat(text)

#> Here's some
#>          multi-line text.
#>
#>          This is on a new line.

uw(text)

#> [1] "Here's some multi-line text.\nThis is on a new line."

cat(.Last.value)

#> Here's some multi-line text.
#> This is on a new line.

uw(text, join = "##")
#> [1] "Here's some##multi-line text.\n##This is on a new line."

cat(.Last.value)
#> Here's some##multi-line text.
#> ##This is on a new line.

long_url <- "http://www.long-api-query.com/ask?
             q=question&
             n=200&
             pg=3"

cat(long_url)
#> http://www.long-api-query.com/ask?
#>     q=question&
#>     n=200&
#>     pg=3

uw0(long_url)
#> [1] "http://www.long-api-query.com/ask?q=question&n=200&pg=3"

DesiQuintans/desiderata documentation built on April 9, 2023, 5:43 a.m.