-
Notifications
You must be signed in to change notification settings - Fork 4
/
search.go
118 lines (92 loc) · 2.43 KB
/
search.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
package main
import (
"errors"
"fmt"
"strings"
"github.com/stretto-editor/gocui"
)
var (
// ErrPatternNotFound raised when the pattern is not found
ErrPatternNotFound = errors.New("Unable to find")
)
func searchHandler(g *gocui.Gui, v *gocui.View) error {
currentDemonInput = func(g *gocui.Gui, input string) (demonInput, error) {
return nil, search(g, input)
}
if v.GetSearchString() == "" {
interactive(g, "Search")
} else {
interactive(g, "Search [" + v.GetSearchString() + "]")
}
return nil
}
func search(g *gocui.Gui, input string) error {
v := g.Workingview()
if found, x, y := v.SearchForward(input); found == true {
v.AbsMoveCursor(x, y, false)
return nil
}
return fmt.Errorf("Could not find pattern \"%s\" forward", v.GetSearchString())
}
func searchAndReplaceHandler(g *gocui.Gui, v *gocui.View) error {
currentDemonInput = func(g *gocui.Gui, input string) (demonInput, error) {
v := g.Workingview()
var x, y int
var found bool
if found, x, y = v.SearchForward(input); !found {
return nil, fmt.Errorf("Could not find pattern \"%s\" forward", input)
}
searched := input
interactive(g, "Search and replace - Replace string")
return func(g *gocui.Gui, input string) (demonInput, error) {
v := g.Workingview()
replaceAt(v, x, y, searched, input)
return nil, nil
}, nil
}
interactive(g, "Search and replace - Search string")
return nil
}
func replaceAll(g *gocui.Gui, pattern, replacement string) {
v := g.Workingview()
v.SetCursor(0, 0)
v.SetOrigin(0, 0)
found, x, y := v.SearchForward(pattern)
for found {
replaceAt(v, x, y, pattern, replacement)
found, x, y = v.SearchForward(pattern)
}
}
func replaceAt(v *gocui.View, x, y int, oldstring, newstring string) {
v.AbsMoveCursor(x, y, false)
for i := 0; i < len(oldstring); i++ {
v.EditDelete(false)
}
for _, c := range newstring {
v.EditWrite(c)
}
}
// func gives how to move from the current origin
func searchForward(v *gocui.View, pattern string, x int, y int) (bool, int, int) {
if len(pattern) > 0 {
var s string
var err error
var sameline = 1
for i := 0; err == nil; i++ {
s, err = v.Line(y + i)
if err == nil {
if x < len(s) {
indice := strings.Index(s[x+sameline:], pattern)
if indice >= 0 {
if sameline == 0 {
return true, indice + sameline, y + i
}
return true, indice + sameline + x, y + i
}
}
x, sameline = 0, 0
}
}
}
return false, 0, 0
}