highlightSpans function

String highlightSpans(
  1. String text,
  2. List<int> indices,
  3. PromptTheme theme
)

Highlights matched spans in text using theme colors.

Implementation

String highlightSpans(String text, List<int> indices, PromptTheme theme) {
  if (indices.isEmpty) return text;
  final set = indices.toSet();
  final buf = StringBuffer();
  bool inSpan = false;
  for (var i = 0; i < text.length; i++) {
    final isMatch = set.contains(i);
    if (isMatch && !inSpan) {
      buf.write(theme.highlight);
      inSpan = true;
    } else if (!isMatch && inSpan) {
      buf.write(theme.reset);
      inSpan = false;
    }
    buf.write(text[i]);
  }
  if (inSpan) buf.write(theme.reset);
  return buf.toString();
}