tidyverse / stringr

A fresh approach to string manipulation in R

Home Page:https://stringr.tidyverse.org

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Function to indent a string (str_indent, perhaps?)

colin-fraser opened this issue · comments

I use stringr extensively for generating code or code-like files (for example, programmatically generating SQL queries), and I often find it helpful to have a function to indent a string. Usually I implement this something like the following.

library(stringi)
str_indent <- function(x, indent_level = 0, indent_character = ' ') {
  indent <- paste(rep(indent_character, indent_level), collapse = '')
  stringi::stri_replace_all_regex(x, '(?m)^', indent)
}
example_text <- paste(month.abb[1:3], collapse = '\n')
cat(example_text)
#> Jan
#> Feb
#> Mar
cat(str_indent(example_text, 3))
#>    Jan
#>    Feb
#>    Mar
# indenting with periods for visibility
cat(str_indent(example_text, 3, '.'))
#> ...Jan
#> ...Feb
#> ...Mar

Created on 2022-11-22 by the reprex package (v2.0.1)

I'd be happy to open a pull request if it seems that this would be sufficiently generally useful.