replaceTabulations function

String replaceTabulations(
  1. String text,
  2. int tabulationSpaceCount
)

Replace tabulations with spaces

Implementation

String replaceTabulations(String text, int tabulationSpaceCount) {
  String replacedText =
      text.replaceAll("\t\t", "\t    ").replaceAll("\n\t", "\n    ");

  if (replacedText.contains('\t')) {
    StringBuffer buffer = StringBuffer();
    int lineCharacterIndex = 0;

    for (int i = 0; i < replacedText.length; i++) {
      String character = replacedText[i];

      if (character == '\t') {
        do {
          buffer.write(' ');
          lineCharacterIndex++;
        } while ((lineCharacterIndex % tabulationSpaceCount) != 0);
      } else {
        buffer.write(character);

        if (character == '\n') {
          lineCharacterIndex = 0;
        } else {
          lineCharacterIndex++;
        }
      }
    }

    return buffer.toString();
  } else {
    return replacedText;
  }
}