-
Notifications
You must be signed in to change notification settings - Fork 16
/
search.go
461 lines (430 loc) · 12.7 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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
package main
import (
"bytes"
"errors"
"fmt"
"os"
"path/filepath"
"strings"
"github.com/xyproto/mode"
"github.com/xyproto/vt100"
)
var (
searchHistoryFilename = filepath.Join(userCacheDir, "o", "search.txt")
searchHistory = []string{}
errNoSearchMatch = errors.New("no search match")
)
// SetSearchTerm will set the current search term to highlight
func (e *Editor) SetSearchTerm(c *vt100.Canvas, status *StatusBar, s string) {
// set the search term
e.searchTerm = s
// set the sticky search term (used by ctrl-n, cleared by Esc only)
e.stickySearchTerm = s
// Go to the first instance after the current line, if found
e.lineBeforeSearch = e.DataY()
for y := e.DataY(); y < LineIndex(e.Len()); y++ {
if strings.Contains(e.Line(y), s) {
// Found an instance, scroll there
// GoTo returns true if the screen should be redrawn
redraw, _ := e.GoTo(y, c, status)
if redraw {
e.Center(c)
}
break
}
}
// draw the lines to the canvas
e.DrawLines(c, true, false)
}
// SearchTerm will return the current search term
func (e *Editor) SearchTerm() string {
return e.searchTerm
}
// ClearSearchTerm will clear the current search term
func (e *Editor) ClearSearchTerm() {
e.searchTerm = ""
}
// UseStickySearchTerm will use the sticky search term as the current search term,
// which is not cleared by Esc, but by ctrl-p.
func (e *Editor) UseStickySearchTerm() {
if e.stickySearchTerm != "" {
e.searchTerm = e.stickySearchTerm
}
}
// ClearStickySearchTerm will clear the sticky search term, for when ctrl-n is pressed.
func (e *Editor) ClearStickySearchTerm() {
e.stickySearchTerm = ""
}
// forwardSearch is a helper function for searching for a string from the given startIndex,
// up to the given stopIndex. -1
// -1 is returned if there are no matches.
// startIndex is expected to be smaller than stopIndex
// x, y is returned.
func (e *Editor) forwardSearch(startIndex, stopIndex LineIndex) (int, LineIndex) {
var (
s = e.SearchTerm()
foundX = -1
foundY = LineIndex(-1)
)
if s == "" {
// Return -1, -1 if no search term is set
return foundX, foundY
}
currentIndex := e.DataY()
// Search from the given startIndex up to the given stopIndex
for y := startIndex; y < stopIndex; y++ {
lineContents := e.Line(y)
if y == currentIndex {
x, err := e.DataX()
if err != nil {
continue
}
// Search from the next byte (not rune) position on this line
// TODO: Move forward one rune instead of one byte
x++
if x >= len(lineContents) {
continue
}
if strings.Contains(lineContents[x:], s) {
foundX = x + strings.Index(lineContents[x:], s)
foundY = y
break
}
} else {
if strings.Contains(lineContents, s) {
foundX = strings.Index(lineContents, s)
foundY = y
break
}
}
}
return foundX, LineIndex(foundY)
}
// backwardSearch is a helper function for searching for a string from the given startIndex,
// backwards to the given stopIndex. -1, -1 is returned if there are no matches.
// startIndex is expected to be larger than stopIndex
func (e *Editor) backwardSearch(startIndex, stopIndex LineIndex) (int, LineIndex) {
var (
s = e.SearchTerm()
foundX = -1
foundY = LineIndex(-1)
)
if len(s) == 0 {
// Return -1, -1 if no search term is set
return foundX, foundY
}
currentIndex := e.DataY()
// Search from the given startIndex backwards up to the given stopIndex
for y := startIndex; y >= stopIndex; y-- {
lineContents := e.Line(y)
if y == currentIndex {
x, err := e.DataX()
if err != nil {
continue
}
// Search from the next byte (not rune) position on this line
// TODO: Move forward one rune instead of one byte
x++
if x >= len(lineContents) {
continue
}
if strings.Contains(lineContents[x:], s) {
foundX = x + strings.Index(lineContents[x:], s)
foundY = y
break
}
} else {
if strings.Contains(lineContents, s) {
foundX = strings.Index(lineContents, s)
foundY = y
break
}
}
}
return foundX, LineIndex(foundY)
}
// GoToNextMatch will go to the next match, searching for "e.SearchTerm()".
// * The search wraps around if wrap is true.
// * The search is backawards if forward is false.
// * The search is case-sensitive.
// Returns an error if the search was successful but no match was found.
func (e *Editor) GoToNextMatch(c *vt100.Canvas, status *StatusBar, wrap, forward bool) error {
var (
foundX int
foundY LineIndex
s = e.SearchTerm()
)
// Check if there's something to search for
if s == "" {
return nil
}
// Search forward or backward
if forward {
// Forward search from the current location
startIndex := e.DataY()
stopIndex := LineIndex(e.Len())
foundX, foundY = e.forwardSearch(startIndex, stopIndex)
} else {
// Backward search form the current location
startIndex := e.DataY()
stopIndex := LineIndex(0)
foundX, foundY = e.backwardSearch(startIndex, stopIndex)
}
if foundY == -1 && wrap {
if forward {
// Do a search from the top if a match was not found
startIndex := LineIndex(0)
stopIndex := LineIndex(e.Len())
foundX, foundY = e.forwardSearch(startIndex, stopIndex)
} else {
// Do a search from the bottom if a match was not found
startIndex := LineIndex(e.Len())
stopIndex := LineIndex(0)
foundX, foundY = e.backwardSearch(startIndex, stopIndex)
}
}
// Check if a match was found
if foundY == -1 {
// Not found
e.GoTo(e.lineBeforeSearch, c, status)
return errNoSearchMatch
}
// Go to the found match
e.redraw, _ = e.GoTo(foundY, c, status)
if foundX != -1 {
tabs := strings.Count(e.Line(foundY), "\t")
e.pos.sx = foundX + (tabs * (e.indentation.PerTab - 1))
e.HorizontalScrollIfNeeded(c)
}
// Center and prepare to redraw
e.Center(c)
e.redraw = true
e.redrawCursor = e.redraw
return nil
}
// SearchMode will enter the interactive "search mode" where the user can type in a string and then press return to search
func (e *Editor) SearchMode(c *vt100.Canvas, status *StatusBar, tty *vt100.TTY, clear bool, undo *Undo) {
var (
searchPrompt = "Search:"
previousSearch string
key string
initialLocation = e.DataY().LineNumber()
searchHistoryIndex int
)
AGAIN:
doneCollectingLetters := false
pressedReturn := false
pressedTab := false
if clear {
// Clear the previous search
e.SetSearchTerm(c, status, "")
}
s := e.SearchTerm()
status.ClearAll(c)
if s == "" {
status.SetMessage(searchPrompt)
} else {
status.SetMessage(searchPrompt + " " + s)
}
status.ShowNoTimeout(c, e)
for !doneCollectingLetters {
key = tty.String()
switch key {
case "c:8", "c:127": // ctrl-h or backspace
if len(s) > 0 {
s = s[:len(s)-1]
if previousSearch == "" {
e.SetSearchTerm(c, status, s)
}
e.GoToLineNumber(initialLocation, c, status, false)
status.SetMessage(searchPrompt + " " + s)
status.ShowNoTimeout(c, e)
}
case "c:27", "c:17": // esc or ctrl-q
s = ""
if previousSearch == "" {
e.SetSearchTerm(c, status, s)
}
doneCollectingLetters = true
case "c:9": // tab
// collect letters again, this time for the replace term
pressedTab = true
doneCollectingLetters = true
case "c:13": // return
pressedReturn = true
doneCollectingLetters = true
case "↑": // previous in the search history
if len(searchHistory) == 0 {
break
}
searchHistoryIndex--
if searchHistoryIndex < 0 {
// wraparound
searchHistoryIndex = len(searchHistory) - 1
}
s = searchHistory[searchHistoryIndex]
if previousSearch == "" {
e.SetSearchTerm(c, status, s)
}
status.SetMessage(searchPrompt + " " + s)
status.ShowNoTimeout(c, e)
case "↓": // next in the search history
if len(searchHistory) == 0 {
break
}
searchHistoryIndex++
if searchHistoryIndex >= len(searchHistory) {
// wraparound
searchHistoryIndex = 0
}
s = searchHistory[searchHistoryIndex]
if previousSearch == "" {
e.SetSearchTerm(c, status, s)
}
status.SetMessage(searchPrompt + " " + s)
status.ShowNoTimeout(c, e)
default:
if key != "" && !strings.HasPrefix(key, "c:") {
s += key
if previousSearch == "" {
e.SetSearchTerm(c, status, s)
}
status.SetMessage(searchPrompt + " " + s)
status.ShowNoTimeout(c, e)
}
}
}
status.ClearAll(c)
// Search settings
forward := true // forward search
wrap := true // with wraparound
// A special case, search backwards to the start of the function (or to "main")
if s == "f" {
switch e.mode {
case mode.Clojure:
s = "defn "
case mode.Crystal, mode.Nim, mode.Python, mode.Scala:
s = "def "
case mode.GDScript, mode.Go:
s = "func "
case mode.Kotlin:
s = "fun "
case mode.Jakt, mode.JavaScript, mode.Koka, mode.Lua, mode.Shell, mode.TypeScript:
s = "function "
case mode.Terra:
s = "terra "
case mode.Odin:
s = "proc() "
case mode.Hare, mode.Rust, mode.V, mode.Zig:
s = "fn "
case mode.Erlang:
// This is not "the definition of a function" in Erlang, but should work for many cases
s = " ->"
case mode.Prolog:
// This is not "the definition of a function" in Prolog, but should work for many cases
s = " :-"
default:
s = "main"
}
forward = false
}
if pressedTab && previousSearch == "" { // search text -> tab
// got the search text, now gather the replace text
previousSearch = e.searchTerm
searchPrompt = "Replace with:"
goto AGAIN
} else if pressedTab && previousSearch != "" { // search text -> tab -> replace text- > tab
undo.Snapshot(e)
// replace once
searchFor := previousSearch
replaceWith := s
replaced := strings.Replace(e.String(), searchFor, replaceWith, 1)
e.LoadBytes([]byte(replaced))
status.messageAfterRedraw = "Replaced " + searchFor + " with " + replaceWith + ", once"
e.redraw = true
return
} else if pressedReturn && previousSearch != "" { // search text -> tab -> replace text -> return
undo.Snapshot(e)
// replace all
searchForBytes := []byte(previousSearch)
replaceWithBytes := []byte(s)
// check if we're searching and replacing an unicode character, like "U+0047" or "u+0000"
if r, err := runeFromUBytes(searchForBytes); err == nil { // success
searchForBytes = []byte(string(r))
}
if r, err := runeFromUBytes(replaceWithBytes); err == nil { // success
replaceWithBytes = []byte(string(r))
}
// perform the replacements, and count the number of instances
allBytes := []byte(e.String())
instanceCount := bytes.Count(allBytes, searchForBytes)
allReplaced := bytes.ReplaceAll(allBytes, searchForBytes, replaceWithBytes)
// replace the contents
e.LoadBytes(allReplaced)
// build a status message
extraS := ""
if instanceCount != 1 {
extraS = "s"
}
status.messageAfterRedraw = fmt.Sprintf("Replaced %d instance%s of %s with %s", instanceCount, extraS, previousSearch, s)
// make sure to redraw after returning
e.redraw = true
return
}
e.SetSearchTerm(c, status, s)
if pressedReturn {
// Return to the first location before performing the actual search
e.GoToLineNumber(initialLocation, c, status, false)
trimmedSearchString := strings.TrimSpace(s)
if len(trimmedSearchString) > 0 {
if lastEntryIsNot(searchHistory, trimmedSearchString) {
searchHistory = append(searchHistory, trimmedSearchString)
}
// ignore errors saving the search history, since it's not critical
if !e.slowLoad {
SaveSearchHistory(searchHistoryFilename, searchHistory)
}
} else if len(searchHistory) > 0 {
s = searchHistory[searchHistoryIndex]
e.SetSearchTerm(c, status, s)
}
}
if previousSearch == "" {
// Perform the actual search
if err := e.GoToNextMatch(c, status, wrap, forward); err == errNoSearchMatch {
// If no match was found, and return was not pressed, try again from the top
//e.GoToTop(c, status)
//err = e.GoToNextMatch(c, status)
if err == errNoSearchMatch {
if wrap {
status.SetMessage(s + " not found")
} else {
status.SetMessage(s + " not found from here")
}
status.ShowNoTimeout(c, e)
}
}
e.Center(c)
}
}
// LoadSearchHistory will load a list of strings from the given filename
func LoadSearchHistory(filename string) ([]string, error) {
data, err := os.ReadFile(filename)
if err != nil {
return []string{}, err
}
// This can load empty words, but they should never be stored in the first place
return strings.Split(string(data), "\n"), nil
}
// SaveSearchHistory will save a list of strings to the given filename
func SaveSearchHistory(filename string, list []string) error {
if len(list) == 0 {
return nil
}
// First create the folder, if needed, in a best effort attempt
folderPath := filepath.Dir(filename)
os.MkdirAll(folderPath, os.ModePerm)
// Then save the data, with strict permissions
data := []byte(strings.Join(list, "\n"))
return os.WriteFile(filename, data, 0600)
}