Left align non-tab indention in R

Viewed 107

Problem

I'm looking for a nice and robust solution to align indention to the second line.

  • second line determines indention size
  • indention is a 2xspace
  • Text may consist 1:n lines

The issue is to compromise a code formatting and expected look of the output.

text <- "first row from 1st col
    no indention
    no indention
    \tindent by \\t\r
    indent 2 spaces"


cat(text)
# first row from 1st col
#     no indention
#     no indention
#         indent by \t
#     indent 2 spaces


cat(gsub("([ ]{2})+", "", text))
# first row from 1st col
# no indention
# no indention
#     indent by \t
# indent 2 spaces

Expected output should look like this

Error: first row always from 1st col
    no indention
    no indention
        indent by \t
      indent 2 spaces

Example solution

I got some solution but it doesn't seem to be elegant

align_left <- function(text) {
  lines <- strsplit(text, "\n")[[1]]
  n_lines <- length(lines)
  if (n_lines > 2) {
    init_indent <- attr(
      regexpr("^[ ]+", lines[2]),
      "match.length"
    )
    
    if (init_indent > 0) {
      for (i in seq(2, n_lines)) {
        lines[i] <- gsub(
          pattern = sprintf("^[ ]{%s}", init_indent), 
          replacement = "", 
          x = lines[i]
        )
      }      
    }
  }
  paste(lines, collapse = "\n")
}

cat(align_left(text))

Example usage

stop(align_left(text))
Error: first row always from 1st col
no indention
no indention
    indent by \t
  indent 2 spaces
0 Answers
Related