previousCharacter static method

  1. @visibleForTesting
int previousCharacter(
  1. int index,
  2. String string, [
  3. bool includeWhitespace = true
])

Returns the index into the string of the previous character boundary before the given index.

The character boundary is determined by the characters package, so surrogate pairs and extended grapheme clusters are considered.

The index must be between 0 and string.length, inclusive. If index is 0, 0 will be returned.

Setting includeWhitespace to false will only return the index of non-space characters.

Implementation

@visibleForTesting
static int previousCharacter(int index, String string,
    [bool includeWhitespace = true]) {
  assert(index >= 0 && index <= string.length);
  if (index == 0) {
    return 0;
  }

  int count = 0;
  int? lastNonWhitespace;
  for (final String currentString in string.characters) {
    if (!includeWhitespace &&
        !TextLayoutMetrics.isWhitespace(
            currentString.characters.first.toString().codeUnitAt(0))) {
      lastNonWhitespace = count;
    }
    if (count + currentString.length >= index) {
      return includeWhitespace ? count : lastNonWhitespace ?? 0;
    }
    count += currentString.length;
  }
  return 0;
}