runes.go 891 B

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. package lipgloss
  2. import (
  3. "strings"
  4. )
  5. // StyleRunes apply a given style to runes at the given indices in the string.
  6. // Note that you must provide styling options for both matched and unmatched
  7. // runes. Indices out of bounds will be ignored.
  8. func StyleRunes(str string, indices []int, matched, unmatched Style) string {
  9. // Convert slice of indices to a map for easier lookups
  10. m := make(map[int]struct{})
  11. for _, i := range indices {
  12. m[i] = struct{}{}
  13. }
  14. var (
  15. out strings.Builder
  16. group strings.Builder
  17. style Style
  18. runes = []rune(str)
  19. )
  20. for i, r := range runes {
  21. group.WriteRune(r)
  22. _, matches := m[i]
  23. _, nextMatches := m[i+1]
  24. if matches != nextMatches || i == len(runes)-1 {
  25. // Flush
  26. if matches {
  27. style = matched
  28. } else {
  29. style = unmatched
  30. }
  31. out.WriteString(style.Render(group.String()))
  32. group.Reset()
  33. }
  34. }
  35. return out.String()
  36. }