runes.go

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