semi working reverse search

This commit is contained in:
Mikael Fangel 2023-04-01 23:38:28 +02:00 committed by Maas Lalani
parent 32d1c21fc1
commit c32d951c2c
No known key found for this signature in database
GPG key ID: 5A6ED5CBF1A0A000

View file

@ -68,7 +68,7 @@ func (s *search) NextMatch(m *model) {
if nextMatch == "" {
// Start the search from the beginning of the document.
s.lastMatchLoc = 0
m.viewport.SetYOffset(0)
m.viewport.GotoTop()
return
}
m.content = m.content[:s.lastMatchLoc] + strings.Replace(m.content[s.lastMatchLoc:], nextMatch, m.matchHighlightStyle.Render(nextMatch), 1)
@ -95,4 +95,59 @@ func (s *search) NextMatch(m *model) {
}
func (s *search) PrevMatch(m *model) {
// Check that we are within bounds.
if s.query == nil {
return
}
// Removed last highlight.
if s.prevMatch != "" {
leftPadding, rightPadding := utils.LipglossLengthPadding(s.prevMatch, m.matchHighlightStyle)
metastring := regexp.QuoteMeta(m.matchHighlightStyle.Render(s.query.String()))
query := regexp.MustCompile("(" + metastring[:leftPadding+1] + ")(" + s.query.String() + ")(" + metastring[len(metastring)-rightPadding-1:] + ")")
m.content = query.ReplaceAllString(m.content, "$2")
}
// Find the string to highlight.
var i int
var nextMatch string
for i = 0; s.query.FindString(m.content[i:s.lastMatchLoc]) != ""; i++ {
nextMatch = s.query.FindString(m.content[:s.lastMatchLoc])
}
s.prevMatch = nextMatch
if nextMatch == "" {
// Start the search from the beginning of the document.
s.lastMatchLoc = m.viewport.TotalLineCount()
m.viewport.GotoTop()
return
}
// m.content = strings.Replace(m.content[:i], nextMatch, m.matchHighlightStyle.Render(nextMatch), 1) + m.content[i:]
// Update the postion of the last found match.
for i = 0; s.query.FindString(m.content[i:s.lastMatchLoc]) != ""; i++ {
}
s.lastMatchLoc = i
// Update the viewport position.
line := 0
for i, c := range m.content {
if c == '\n' {
line++
}
if i == s.lastMatchLoc {
break
}
}
// Only update if the match is not within the viewport
if line > m.viewport.YOffset+m.viewport.VisibleLineCount()-1 || line < m.viewport.YOffset {
m.viewport.SetYOffset(line)
}
}
func Reverse(s string) (result string) {
for _, v := range s {
result = string(v) + result
}
return
}