Skip to content

Commit

Permalink
Add replace_leading_whitespace function
Browse files Browse the repository at this point in the history
  • Loading branch information
mstackhouse committed Dec 19, 2023
1 parent 5e1dcf2 commit 268a623
Showing 1 changed file with 28 additions and 0 deletions.
28 changes: 28 additions & 0 deletions R/replace_leading_whitespace.R
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 &nbsp; string and combine with the trimmed string
nbsp_string <- map_chr(leading_length, \(.x) paste(rep("&nbsp;", .x), collapse=""))
minus_whitespace <- stringr::str_trim(x, side=left)
paste(nbsp_string, minus_whitespace, sep="")
}

0 comments on commit 268a623

Please sign in to comment.