fixText property

String get fixText

Fixes the given value by applying various text formatting rules.

The method performs the following operations on the input value:

  • If the value is blank, it returns a blank string.
  • Trims leading and trailing whitespace from the value.
  • Adds a space after punctuation or comma, if not already present.
  • Replaces a comma at the end of the value with a dot.
  • Adds a space before a hyphen if it is followed by a space.
  • Ensures that the sentence ends with a dot if it doesn't end with any punctuation.
  • Ensures that the first characters after a punctuation are uppercase (ignoring whitespace).
  • Ensures that the first character of the sentence is uppercase.

Returns the fixed text value.

Implementation

String get fixText {
  var value = this;
  if (value.isBlank) {
    return blankIfNull;
  }

  // split lines ang guarantee the first letter in each line is uppercase and the last character is a punctuation. if last char is not a punctuation, add a dot
  value = value.splitLines.map((line) {
    line = line.trimAll;

    if (line.isBlank) {
      return "";
    }

    line = line.fixQuotes;

    // Add space after closing parenthesis, closing brackets, punctuation or comma, if not is any of following chars (using replaceAllMapped):
    // )]}!?:;.,
    line = line.replaceAllMapped(RegExp(r'([)\]}!?:;.,])([^ )\]}!?:;.,])'), (match) => '${match.group(1)} ${match.group(2)}');

    line = line.trim();

    // Replace comma at the end with a dot
    if (line.endsWith(',')) {
      line = '${line.substring(0, line.length - 1)}.';
    }

    // if value contains a - followed by a space, add a space before the - if not exist
    line = line.replaceAllMapped(RegExp(r'(?<!\s)-\s'), (match) => ' - ');

    // Ensure the sentence ends with a dot if it doesn't end with any punctuation
    if (!RegExp(r'[.!?]$').hasMatch(line)) {
      line += '.';
    }

    // Ensure the first characters after a punctuation are uppercase (ignore whitespace)
    line = line.replaceAllMapped(RegExp(r'([.!?])\s*([a-z])'), (match) => '${match.group(1)} ${match.group(2)?.toUpperCase()}');

    // Ensure the first character of sentece is uppercase
    line = "${line.first().toUpperCase()}${line.substring(1)}";

    return line;
  }).join("\r\n");

  return value;
}