format method

void format(
  1. String input, {
  2. bool leadingSpace = true,
  3. bool trailingNewline = true,
  4. bool trimIndentation = true,
})

Replaces the newlines and tabs of input and adds it to the stream.

trimIndentation flag finds the line with the fewest leading empty spaces and trims the beginning of all lines by this number.

Implementation

void format(
  String input, {
  bool leadingSpace = true,
  bool trailingNewline = true,
  bool trimIndentation = true,
}) {
  final List<String> lines = input.split('\n');

  final int indentationToRemove = !trimIndentation
      ? 0
      : lines
          .where((String line) => line.trim().isNotEmpty)
          .map((String line) => line.length - line.trimLeft().length)
          .reduce(min);

  for (int i = 0; i < lines.length; ++i) {
    final String line = lines[i].length >= indentationToRemove
        ? lines[i].substring(indentationToRemove)
        : lines[i];

    if (i == 0 && !leadingSpace) {
      add(line.replaceAll('\t', tab));
    } else if (line.isNotEmpty) {
      write(line.replaceAll('\t', tab));
    }
    if (trailingNewline || i < lines.length - 1) {
      addln('');
    }
  }
}