-
Notifications
You must be signed in to change notification settings - Fork 17
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add replace_leading_whitespace function
- Loading branch information
1 parent
5e1dcf2
commit 268a623
Showing
1 changed file
with
28 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,28 @@ | ||
#' Reformat strings with leading whitespace for HTML | ||
#' | ||
#' @param x Target string | ||
#' @param tab_width Number of spaces to compensate for tabs | ||
#' | ||
#' @return String with replaced for leading whitespace | ||
#' @export | ||
#' | ||
#' @examples | ||
#' x <- c(" Hello there", " Goodbye Friend ", "\tNice to meet you", " \t What are you up to? \t \t ") | ||
#' replace_leading_whitespace(x) | ||
#' | ||
#' replace_leading_whitespace(x, tab=2) | ||
#' | ||
replace_leading_whitespace <- function(x, tab_width=4) { | ||
# Pull out the leading whitespace chunk | ||
leading_spaces <- stringr::str_match(x, "^([ \\t])+")[,1] | ||
# Count spaces and tabs, factor in tab width | ||
spaces <- stringr::str_count(leading_spaces, pattern = " ") | ||
tabs <- stringr::str_count(leading_spaces, pattern = "\\t") * tab_width | ||
leading_length <- as.integer(spaces + tabs) | ||
|
||
# Build the string and combine with the trimmed string | ||
nbsp_string <- map_chr(leading_length, \(.x) paste(rep(" ", .x), collapse="")) | ||
minus_whitespace <- stringr::str_trim(x, side=left) | ||
paste(nbsp_string, minus_whitespace, sep="") | ||
} | ||
|