getCleanedText method

String getCleanedText(
  1. String text,
  2. int tabSpaceCount
)

Get cleaned text with tabulations replaced with spaces

Implementation

String getCleanedText(String text, int tabSpaceCount) {
  // Replace tab characters with spaces
  String cleanedText = text;

  // Replace tab+tab with tab+spaces
  cleanedText = cleanedText.replaceAll("\t\t", "\t    ");
  cleanedText = cleanedText.replaceAll("\n\t", "\n    ");

  if (cleanedText.contains('\t')) {
    String replacedText = "";
    int lineCharacterIndex = 0;

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

      if (character == '\t') {
        do {
          replacedText += ' ';
          lineCharacterIndex++;
        } while ((lineCharacterIndex % tabSpaceCount) != 0);
      } else {
        replacedText += character;

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

    cleanedText = replacedText;
  }

  // Remove carriage returns and ensure the text ends with a newline
  cleanedText = cleanedText.replaceAll("\r", "");

  if (!cleanedText.endsWith('\n')) {
    cleanedText += '\n';
  }

  return cleanedText;
}