expandTabs method

String expandTabs([
  1. int tabSize = 8
])

Returns a copy where all tab characters are expanded using spaces.

Each tab character is replaced with enough spaces to reach the next tab stop, which occurs every tabSize columns. The column position is reset at the beginning of each line (after CR or LF characters).

Example:

final text = 'hello\tworld';
final expanded = text.expandTabs(4);
// Returns: 'hello    world' (assuming 'hello' is 5 chars, adds 3 spaces)

Implementation

String expandTabs([int tabSize = 8]) {
  var buffer = StringBuffer();
  var units = runes.toList();
  var length = units.length;

  for (var i = 0, line = 0; i < length; i += 1, line += 1) {
    var char = units[i];

    if (char == 13 || char == 10) {
      line = -1;
      buffer.writeCharCode(char);
    } else if (char == 9) {
      var size = tabSize - (line % tabSize);
      buffer.write(' ' * size);
      line = -1;
    } else {
      buffer.writeCharCode(char);
    }
  }

  return buffer.toString();
}