search.go
This file
Path
pager/search.go
178 lines · 4.8 KiB · Go
Last changed by
chore: update to bubbletea v2 (#1112)Drew Smirnoffbefore adoptionf6dd28e
History of this fileTake it
1package pager23import (4 "fmt"5 "regexp"6 "strings"78 "charm.land/bubbles/v2/textinput"9 "charm.land/lipgloss/v2"10 "github.com/charmbracelet/x/ansi"11)1213type search struct {14 active bool15 input textinput.Model16 query *regexp.Regexp17 matchIndex int18 matchLipglossStr string19 matchString string20}2122func (s *search) new() {23 input := textinput.New()24 input.Placeholder = "search"25 input.Prompt = "/"26 styles := input.Styles()27 styles.Focused.Prompt = lipgloss.NewStyle().Foreground(lipgloss.Color("240"))28 styles.Blurred.Prompt = lipgloss.NewStyle().Foreground(lipgloss.Color("240"))29 input.SetStyles(styles)30 s.input = input31}3233func (s *search) Begin() {34 s.new()35 s.active = true36 s.input.Focus()37}3839// Execute find all lines in the model with a match.40func (s *search) Execute(m *model) {41 defer s.Done()42 if s.input.Value() == "" {43 s.query = nil44 return45 }4647 var err error48 s.query, err = regexp.Compile(s.input.Value())49 if err != nil {50 s.query = nil51 return52 }53 query := regexp.MustCompile(fmt.Sprintf("(%s)", s.query.String()))54 m.content = query.ReplaceAllString(m.content, m.matchStyle.Render("$1"))5556 // Recompile the regex to match the an replace the highlights.57 leftPad, _ := lipglossPadding(m.matchStyle)58 matchingString := regexp.QuoteMeta(m.matchStyle.Render()[:leftPad]) + s.query.String() + regexp.QuoteMeta(m.matchStyle.Render()[leftPad:])59 s.query, err = regexp.Compile(matchingString)60 if err != nil {61 s.query = nil62 }63}6465func (s *search) Done() {66 s.active = false6768 // To account for the first match is always executed.69 s.matchIndex = -170}7172func (s *search) NextMatch(m *model) {73 // Check that we are within bounds.74 if s.query == nil {75 return76 }7778 // Remove previous highlight.79 m.content = strings.Replace(m.content, s.matchLipglossStr, s.matchString, 1)8081 // Highlight the next match.82 allMatches := s.query.FindAllStringIndex(m.content, -1)83 if len(allMatches) == 0 {84 return85 }8687 leftPad, rightPad := lipglossPadding(m.matchStyle)88 s.matchIndex = (s.matchIndex + 1) % len(allMatches)89 match := allMatches[s.matchIndex]90 lhs := m.content[:match[0]]91 rhs := m.content[match[0]:]92 s.matchString = m.content[match[0]:match[1]]93 s.matchLipglossStr = m.matchHighlightStyle.Render(s.matchString[leftPad : len(s.matchString)-rightPad])94 m.content = lhs + strings.Replace(rhs, m.content[match[0]:match[1]], s.matchLipglossStr, 1)9596 // Update the viewport position.97 var line int98 formatStr := softWrapEm(m.content, m.maxWidth, m.softWrap)99 index := strings.Index(formatStr, s.matchLipglossStr)100 if index != -1 {101 line = strings.Count(formatStr[:index], "\n")102 }103104 // Only update if the match is not within the viewport.105 if index != -1 && (line > m.viewport.YOffset()-1+m.viewport.VisibleLineCount()-1 || line < m.viewport.YOffset()) {106 m.viewport.SetYOffset(line)107 }108}109110func (s *search) PrevMatch(m *model) {111 // Check that we are within bounds.112 if s.query == nil {113 return114 }115116 // Remove previous highlight.117 m.content = strings.Replace(m.content, s.matchLipglossStr, s.matchString, 1)118119 // Highlight the previous match.120 allMatches := s.query.FindAllStringIndex(m.content, -1)121 if len(allMatches) == 0 {122 return123 }124125 s.matchIndex = (s.matchIndex - 1) % len(allMatches)126 if s.matchIndex < 0 {127 s.matchIndex = len(allMatches) - 1128 }129130 leftPad, rightPad := lipglossPadding(m.matchStyle)131 match := allMatches[s.matchIndex]132 lhs := m.content[:match[0]]133 rhs := m.content[match[0]:]134 s.matchString = m.content[match[0]:match[1]]135 s.matchLipglossStr = m.matchHighlightStyle.Render(s.matchString[leftPad : len(s.matchString)-rightPad])136 m.content = lhs + strings.Replace(rhs, m.content[match[0]:match[1]], s.matchLipglossStr, 1)137138 // Update the viewport position.139 var line int140 formatStr := softWrapEm(m.content, m.maxWidth, m.softWrap)141 index := strings.Index(formatStr, s.matchLipglossStr)142 if index != -1 {143 line = strings.Count(formatStr[:index], "\n")144 }145146 // Only update if the match is not within the viewport.147 if index != -1 && (line > m.viewport.YOffset()-1+m.viewport.VisibleLineCount()-1 || line < m.viewport.YOffset()) {148 m.viewport.SetYOffset(line)149 }150}151152func softWrapEm(str string, maxWidth int, softWrap bool) string {153 var text strings.Builder154 for _, line := range strings.Split(str, "\n") {155 idx := 0156 if w := ansi.StringWidth(line); softWrap && w > maxWidth {157 for w > idx {158 truncatedLine := ansi.Cut(line, idx, maxWidth+idx)159 idx += maxWidth160 text.WriteString(truncatedLine)161 text.WriteString("\n")162 }163 } else {164 text.WriteString(line)165 text.WriteString("\n")166 }167 }168169 return text.String()170}171172// lipglossPadding calculates how much padding a string is given by a style.173func lipglossPadding(style lipgloss.Style) (int, int) {174 render := style.Render(" ")175 before := strings.Index(render, " ")176 after := len(render) - len(" ") - before177 return before, after178}