@@ -2,25 +2,60 @@ package list
22
33import (
44 "image"
5+ "strings"
56
67 "charm.land/lipgloss/v2"
78 uv "github.com/charmbracelet/ultraviolet"
89)
910
1011// DefaultHighlighter is the default highlighter function that applies inverse style.
11−var DefaultHighlighter Highlighter = func(s uv.Style) uv.Style {
12− s.Attrs |= uv.AttrReverse
13− return s
12+var DefaultHighlighter Highlighter = func(x, y int, c *uv.Cell) *uv.Cell {
13+ if c == nil {
14+ return c
15+ }
16+ c.Style.Attrs |= uv.AttrReverse
17+ return c
1418}
1519
1620// Highlighter represents a function that defines how to highlight text.
17−type Highlighter func(uv.Style) uv.Style
21+type Highlighter func(x, y int, c *uv.Cell) *uv.Cell
22+
23+// HighlightContent returns the content with highlighted regions based on the specified parameters.
24+func HighlightContent(content string, area image.Rectangle, startLine, startCol, endLine, endCol int) string {
25+ var sb strings.Builder
26+ pos := image.Pt(-1, -1)
27+ HighlightBuffer(content, area, startLine, startCol, endLine, endCol, func(x, y int, c *uv.Cell) *uv.Cell {
28+ pos.X = x
29+ if pos.Y == -1 {
30+ pos.Y = y
31+ } else if y > pos.Y {
32+ sb.WriteString(strings.Repeat("\n", y-pos.Y))
33+ pos.Y = y
34+ }
35+ sb.WriteString(c.Content)
36+ return c
37+ })
38+ if sb.Len() > 0 {
39+ sb.WriteString("\n")
40+ }
41+ return sb.String()
42+}
1843
1944// Highlight highlights a region of text within the given content and region.
2045func Highlight(content string, area image.Rectangle, startLine, startCol, endLine, endCol int, highlighter Highlighter) string {
21− if startLine < 0 || startCol < 0 {
46+ buf := HighlightBuffer(content, area, startLine, startCol, endLine, endCol, highlighter)
47+ if buf == nil {
2248 return content
2349 }
50+ return buf.Render()
51+}
52+
53+// HighlightBuffer highlights a region of text within the given content and
54+// region, returning a [uv.ScreenBuffer].
55+func HighlightBuffer(content string, area image.Rectangle, startLine, startCol, endLine, endCol int, highlighter Highlighter) *uv.ScreenBuffer {
56+ if startLine < 0 || startCol < 0 {
57+ return nil
58+ }
2459
2560 if highlighter == nil {
2661 highlighter = DefaultHighlighter
@@ -87,17 +122,22 @@ func Highlight(content string, area image.Rectangle, startLine, startCol, endLin
87122 continue
88123 }
89124 cell := line.At(x)
90− cell.Style = highlighter(cell.Style)
125+ if cell != nil {
126+ line.Set(x, highlighter(x, y, cell))
127+ }
91128 }
92129 }
93130
94− return buf.Render()
131+ return &buf
95132}
96133
97134// ToHighlighter converts a [lipgloss.Style] to a [Highlighter].
98135func ToHighlighter(lgStyle lipgloss.Style) Highlighter {
99− return func(uv.Style) uv.Style {
100− return ToStyle(lgStyle)
136+ return func(_ int, _ int, c *uv.Cell) *uv.Cell {
137+ if c != nil {
138+ c.Style = ToStyle(lgStyle)
139+ }
140+ return c
101141 }
102142}
103143