applyToString method

SpanList applyToString(
  1. SpannedString source, {
  2. bool clearPrevious = true,
})

Apply the formatting rules to source and return the resulting SpanList.

Implementation

SpanList applyToString(SpannedString source, {bool clearPrevious = true}) {
  final text = source.text.string;
  var spans = source.spans;
  if (clearPrevious) {
    spans = spans.removeType<AutoFormatTextAttribute>();
  }

  for (final rule in rules) {
    final matches = rule.exp.allMatches(text);
    for (final match in matches) {
      // Zero-length spans are not allowed, so we filter out zero-length
      // matches.
      if (match.end == match.start) {
        continue;
      }

      // We have to do some index translation here because regex returns
      // UTF-16 character indices, but we use ECG (with the characters
      // package).

      final chars = CharacterRange.at(text, match.start, match.end);
      final start = chars.charactersBefore.length;
      final end = start + chars.currentCharacters.length;
      final attribute = AutoFormatTextAttribute(rule.matchToAttribute(match));
      final span = AttributeSpan(attribute, start, end);
      spans = spans.merge(span);
    }
  }

  return spans;
}