Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Function to indent a string (str_indent, perhaps?) #480

Open
colin-fraser opened this issue Nov 22, 2022 · 0 comments
Open

Function to indent a string (str_indent, perhaps?) #480

colin-fraser opened this issue Nov 22, 2022 · 0 comments
Labels
feature a feature request or enhancement

Comments

@colin-fraser
Copy link

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.

@hadley hadley added the feature a feature request or enhancement label Aug 4, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
feature a feature request or enhancement
Projects
None yet
Development

No branches or pull requests

2 participants