removeHangingIndent method

String removeHangingIndent(
  1. String indentation
)

Removes indentation from all lines except the first.

Pairs with hangingIndent to undo hanging indentation formatting. Lines without the matching indentation are left unchanged.

Example:

'line1\n  line2\n  line3'.removeHangingIndent('  ')
// 'line1\nline2\nline3'

'first\n  second\n  third'.removeHangingIndent('  ')
// 'first\nsecond\nthird'

Implementation

String removeHangingIndent(String indentation) {
  if (isEmpty || indentation.isEmpty) return this;
  final lines = split('\n');
  if (lines.length == 1) return this;
  return [
    lines.first,
    ...lines.skip(1).map((line) {
      if (line.startsWith(indentation)) {
        return line.substring(indentation.length);
      }
      return line;
    })
  ].join('\n');
}