Debian Codegraph @

nav.go

raw
1 package main
2
3 import (
4 "bufio"
5 "bytes"
6 "cmp"
7 "errors"
8 "fmt"
9 "io"
10 "log"
11 "maps"
12 "os"
13 "os/exec"
14 "path/filepath"
15 "regexp"
16 "slices"
17 "strconv"
18 "strings"
19 "time"
20
21 "github.com/djherbis/times"
22 )
23
24 // A linkState describes whether a file is a symlink and whether its target exists.
25 type linkState byte
26
27 const (
28 notLink linkState = iota // Not a symbolic link.
29 working // Symbolic link with an existing target.
30 broken // Symbolic link with a missing target.
31 )
32
33 type file struct {
34 os.FileInfo // stat information
35 linkState linkState // symlink state
36 linkTarget string // path a symlink points to
37 path string // full path including the name
38 dirCount int // number of items inside the directory
39 dirSize int64 // total directory size (needs to be calculated via `calcdirsize`)
40 accessTime time.Time // time of last access
41 birthTime time.Time // time of file birth
42 changeTime time.Time // time of last status (inode) change
43 customInfo string // property defined via `addcustominfo`
44 ext string // file extension (including the dot)
45 err error // potential error returned by [os.Lstat]
46 }
47
48 func newFile(path string) *file {
49 lstat, err := os.Lstat(path)
50 if err != nil {
51 log.Printf("getting file information: %s", err)
52 return &file{
53 FileInfo: &fakeStat{name: filepath.Base(path)},
54 linkState: notLink,
55 path: path,
56 dirCount: -1,
57 dirSize: -1,
58 accessTime: time.Unix(0, 0),
59 birthTime: time.Unix(0, 0),
60 changeTime: time.Unix(0, 0),
61 err: err,
62 }
63 }
64
65 var linkState linkState
66 var linkTarget string
67
68 if lstat.Mode()&os.ModeSymlink != 0 {
69 stat, err := os.Stat(path)
70 if err == nil {
71 linkState = working
72 lstat = stat
73 } else {
74 linkState = broken
75 }
76 linkTarget, err = os.Readlink(path)
77 if err != nil {
78 log.Printf("reading link target: %s", err)
79 }
80 }
81
82 ts := times.Get(lstat)
83 at := ts.AccessTime()
84 // from [times.Timespec] docs:
85 // ChangeTime() panics unless HasChangeTime() is true and
86 // BirthTime() panics unless HasBirthTime() is true.
87
88 // default to ModTime if BirthTime cannot be determined
89 bt := lstat.ModTime()
90 if ts.HasBirthTime() {
91 bt = ts.BirthTime()
92 }
93 // default to ModTime if ChangeTime cannot be determined
94 ct := lstat.ModTime()
95 if ts.HasChangeTime() {
96 ct = ts.ChangeTime()
97 }
98
99 dirCount := -1
100 if lstat.IsDir() && getDirCounts(filepath.Dir(path)) {
101 d, err := os.Open(path)
102 if err != nil {
103 log.Printf("opening file: %s", err)
104 } else {
105 names, err := d.Readdirnames(10000)
106 d.Close()
107
108 if names == nil && err != io.EOF {
109 log.Printf("reading directory: %s", err)
110 } else {
111 dirCount = len(names)
112 }
113 }
114 }
115
116 return &file{
117 FileInfo: lstat,
118 linkState: linkState,
119 linkTarget: linkTarget,
120 path: path,
121 dirCount: dirCount,
122 dirSize: -1,
123 accessTime: at,
124 birthTime: bt,
125 changeTime: ct,
126 ext: getFileExtension(lstat),
127 }
128 }
129
130 func (file *file) isPreviewable() bool {
131 return !file.IsDir() || gOpts.dirpreviews
132 }
133
134 type fakeStat struct {
135 name string
136 }
137
138 func (fs *fakeStat) Name() string { return fs.name }
139 func (fs *fakeStat) Size() int64 { return 0 }
140 func (fs *fakeStat) Mode() os.FileMode { return os.FileMode(0o000) }
141 func (fs *fakeStat) ModTime() time.Time { return time.Unix(0, 0) }
142 func (fs *fakeStat) IsDir() bool { return false }
143 func (fs *fakeStat) Sys() any { return nil }
144
145 func readdir(path string) ([]*file, error) {
146 f, err := os.Open(path)
147 if err != nil {
148 return nil, err
149 }
150 names, err := f.Readdirnames(-1)
151 f.Close()
152
153 files := make([]*file, 0, len(names))
154 for _, fname := range names {
155 file := newFile(filepath.Join(path, fname))
156 if !os.IsNotExist(file.err) {
157 files = append(files, file)
158 }
159 }
160
161 return files, err
162 }
163
164 type dir struct {
165 loading bool // whether directory is loading from disk
166 loadTime time.Time // last load time
167 ind int // 0-based index of current entry in dir.files
168 pos int // 0-based cursor row in directory window
169 path string // full path of directory
170 files []*file // displayed files in directory including or excluding hidden ones
171 allFiles []*file // all files in directory including hidden ones (same array as files)
172 sortby sortMethod // sortby value from last sort
173 dircounts bool // dircounts value from last sort
174 dirfirst bool // dirfirst value from last sort
175 dironly bool // dironly value from last sort
176 hidden bool // hidden value from last sort
177 reverse bool // reverse value from last sort
178 visualAnchor int // index where Visual mode was initiated
179 visualWrap int // wrap direction in Visual mode (0: none, +: bottom->top, -: top->bottom)
180 hiddenfiles []string // hiddenfiles value from last sort
181 filter []string // last filter for this directory
182 sortignorecase bool // sortignorecase value from last sort
183 sortignoredia bool // sortignoredia value from last sort
184 noPerm bool // whether lf has no permission to open the directory
185 }
186
187 func newDir(path string) *dir {
188 files, err := readdir(path)
189 if err != nil {
190 log.Printf("reading directory: %s", err)
191 }
192
193 return &dir{
194 loadTime: time.Now(),
195 path: path,
196 files: files,
197 allFiles: files,
198 visualAnchor: -1,
199 noPerm: os.IsPermission(err),
200 }
201 }
202
203 func (dir *dir) sort() {
204 dir.sortby = getSortBy(dir.path)
205 dir.dircounts = getDirCounts(dir.path)
206 dir.dirfirst = getDirFirst(dir.path)
207 dir.dironly = getDirOnly(dir.path)
208 dir.hidden = getHidden(dir.path)
209 dir.reverse = getReverse(dir.path)
210 dir.hiddenfiles = gOpts.hiddenfiles
211 dir.sortignorecase = getSortIgnoreCase(dir.path)
212 dir.sortignoredia = getSortIgnoreDia(dir.path)
213
214 dir.files = dir.allFiles
215
216 // When applying a filter, move all files not satisfying the predicate to
217 // the beginning, then take the subslice starting from the first file that
218 // does satisfy the predicate
219 applyFilter := func(fn func(f *file) bool) {
220 slices.SortStableFunc(dir.files, func(i, j *file) int {
221 switch {
222 case !fn(i) && fn(j):
223 return -1
224 case fn(i) && !fn(j):
225 return 1
226 default:
227 return 0
228 }
229 })
230
231 i := slices.IndexFunc(dir.files, fn)
232 if i == -1 {
233 i = len(dir.files)
234 }
235 dir.files = dir.files[i:]
236 }
237
238 if dir.dironly {
239 applyFilter(func(f *file) bool { return f.IsDir() })
240 }
241
242 if !dir.hidden {
243 applyFilter(func(f *file) bool { return !isHidden(f, dir.path, dir.hiddenfiles) })
244 }
245
246 if len(dir.filter) != 0 {
247 applyFilter(func(f *file) bool { return !isFiltered(f, dir.filter) })
248 }
249
250 applySort := func(fn func(f1, f2 *file) int) {
251 if !dir.reverse {
252 slices.SortStableFunc(dir.files, fn)
253 } else {
254 slices.SortStableFunc(dir.files, func(f1, f2 *file) int { return fn(f2, f1) })
255 }
256 }
257
258 normalize := func(s string) string {
259 if dir.sortignorecase {
260 s = strings.ToLower(s)
261 }
262 if dir.sortignoredia {
263 s = removeDiacritics(s)
264 }
265 return s
266 }
267
268 switch dir.sortby {
269 case naturalSort:
270 applySort(func(f1, f2 *file) int {
271 return naturalCmp(normalize(f1.Name()), normalize(f2.Name()))
272 })
273 case nameSort:
274 applySort(func(f1, f2 *file) int {
275 return cmp.Compare(normalize(f1.Name()), normalize(f2.Name()))
276 })
277 case sizeSort:
278 sizeVal := func(f *file) int64 {
279 if f.IsDir() && dir.dircounts {
280 return int64(f.dirCount)
281 }
282 if f.dirSize >= 0 {
283 return f.dirSize
284 }
285 return f.Size()
286 }
287 applySort(func(f1, f2 *file) int {
288 return cmp.Compare(sizeVal(f1), sizeVal(f2))
289 })
290 case timeSort:
291 applySort(func(f1, f2 *file) int {
292 return f1.ModTime().Compare(f2.ModTime())
293 })
294 case atimeSort:
295 applySort(func(f1, f2 *file) int {
296 return f1.accessTime.Compare(f2.accessTime)
297 })
298 case btimeSort:
299 applySort(func(f1, f2 *file) int {
300 return f1.birthTime.Compare(f2.birthTime)
301 })
302 case ctimeSort:
303 applySort(func(f1, f2 *file) int {
304 return f1.changeTime.Compare(f2.changeTime)
305 })
306 case extSort:
307 applySort(func(f1, f2 *file) int {
308 ext1 := normalize(f1.ext)
309 ext2 := normalize(f2.ext)
310 if ext1 != ext2 {
311 return cmp.Compare(ext1, ext2)
312 }
313 return cmp.Compare(normalize(f1.Name()), normalize(f2.Name()))
314 })
315 case customSort:
316 applySort(func(f1, f2 *file) int {
317 s1 := normalize(stripTermSequence(f1.customInfo))
318 s2 := normalize(stripTermSequence(f2.customInfo))
319 return naturalCmp(s1, s2)
320 })
321 }
322
323 // when sorting by size while also showing dircounts, we always display files
324 // and directories separately to avoid mixing file sizes and file counts
325 if dir.dirfirst || (dir.sortby == sizeSort && dir.dircounts) {
326 slices.SortStableFunc(dir.files, func(f1, f2 *file) int {
327 switch {
328 case f1.IsDir() && !f2.IsDir():
329 return -1
330 case !f1.IsDir() && f2.IsDir():
331 return 1
332 default:
333 return 0
334 }
335 })
336 }
337
338 dir.ind = max(dir.ind, 0)
339 dir.ind = min(dir.ind, len(dir.files)-1)
340 }
341
342 func (dir *dir) name() string {
343 if len(dir.files) == 0 {
344 return ""
345 }
346
347 return dir.files[dir.ind].Name()
348 }
349
350 func (nav *nav) isVisualMode() bool {
351 return nav.currDir().visualAnchor != -1
352 }
353
354 func (dir *dir) visualSelections() []string {
355 paths := []string{}
356 if dir.visualAnchor == -1 || len(dir.files) == 0 {
357 return paths
358 }
359
360 var beg, end int
361 switch {
362 case dir.visualWrap == 0:
363 beg = min(dir.ind, dir.visualAnchor)
364 end = max(dir.ind, dir.visualAnchor)
365 case dir.visualWrap < 0:
366 beg = dir.ind
367 end = dir.visualAnchor - dir.visualWrap*len(dir.files)
368 case dir.visualWrap > 0:
369 beg = dir.visualAnchor
370 end = dir.ind + dir.visualWrap*len(dir.files)
371 }
372
373 for i := beg; i < min(end+1, beg+len(dir.files)); i++ {
374 paths = append(paths, dir.files[i%len(dir.files)].path)
375 }
376
377 return paths
378 }
379
380 func (dir *dir) sel(name string, height int) {
381 if len(dir.files) == 0 {
382 dir.ind, dir.pos = 0, 0
383 return
384 }
385
386 dir.ind = max(dir.ind, 0)
387 dir.ind = min(dir.ind, len(dir.files)-1)
388
389 if dir.files[dir.ind].Name() != name {
390 for i, f := range dir.files {
391 if f.Name() == name {
392 dir.ind = i
393 break
394 }
395 }
396 }
397
398 dir.boundPos(height)
399 }
400
401 func (dir *dir) boundPos(height int) {
402 if len(dir.files) <= height {
403 dir.pos = dir.ind
404 return
405 }
406
407 edge := min(height/2, gOpts.scrolloff)
408 dir.pos = max(dir.pos, edge)
409
410 // use a smaller value for half when the height is even and scrolloff is
411 // maxed in order to stay at the same row while scrolling up and down
412 if height%2 == 0 {
413 edge = min(height/2-1, gOpts.scrolloff)
414 }
415 dir.pos = min(dir.pos, height-1-edge)
416
417 dir.pos = min(dir.pos, dir.ind)
418 dir.pos = max(dir.pos, height-(len(dir.files)-dir.ind))
419 }
420
421 // clipboardMode controls the clipboard's behavior when pasting.
422 type clipboardMode byte
423
424 const (
425 clipboardCopy clipboardMode = iota // Copy on paste.
426 clipboardCut // Move on paste.
427 )
428
429 type clipboard struct {
430 paths []string
431 mode clipboardMode
432 }
433
434 type nav struct {
435 dirPaths []string
436 copyJobs int
437 copyBytes int64
438 copyTotal int64
439 copyUpdate int
440 moveCount int
441 moveTotal int
442 moveUpdate int
443 deleteCount int
444 deleteTotal int
445 deleteUpdate int
446 copyJobsChan chan int
447 copyBytesChan chan int64
448 copyTotalChan chan int64
449 moveCountChan chan int
450 moveTotalChan chan int
451 deleteCountChan chan int
452 deleteTotalChan chan int
453 preloadChan chan string
454 previewChan chan string
455 dirChan chan *dir
456 regChan chan *reg
457 fileChan chan *file
458 delChan chan string
459 dirCache map[string]*dir
460 regCache map[string]*reg
461 clipboard clipboard
462 marks map[string]string
463 renameOldPath string
464 renameNewPath string
465 selections map[string]int
466 tags map[string]string
467 selectionInd int
468 height int
469 previewWidth int
470 find string
471 findBack bool
472 search string
473 searchBack bool
474 searchInd int
475 searchPos int
476 prevFilter []string
477 volatilePreview bool
478 previewTimer *time.Timer
479 preloadTimer *time.Timer
480 jumpList []string
481 jumpListInd int
482 }
483
484 func (nav *nav) getDir(path string) *dir {
485 if d, ok := nav.dirCache[path]; ok {
486 return d
487 }
488
489 go func() {
490 nav.dirChan <- newDir(path)
491 }()
492
493 d := &dir{
494 loading: true,
495 loadTime: time.Now(),
496 path: path,
497 sortby: getSortBy(path),
498 dircounts: getDirCounts(path),
499 dirfirst: getDirFirst(path),
500 dironly: getDirOnly(path),
501 hidden: getHidden(path),
502 reverse: getReverse(path),
503 visualAnchor: -1,
504 hiddenfiles: gOpts.hiddenfiles,
505 sortignorecase: getSortIgnoreCase(path),
506 sortignoredia: getSortIgnoreDia(path),
507 }
508 nav.dirCache[path] = d
509 return d
510 }
511
512 func (nav *nav) checkDir(dir *dir) {
513 if dir.loading {
514 return
515 }
516
517 s, err := os.Stat(dir.path)
518 if err != nil {
519 log.Printf("getting directory info: %s", err)
520 return
521 }
522
523 switch {
524 case s.ModTime().After(dir.loadTime):
525 // XXX: Linux builtin exFAT drivers are able to predict modifications in the future
526 // https://bugs.launchpad.net/ubuntu/+source/ubuntu-meta/+bug/1872504
527 if s.ModTime().After(time.Now()) {
528 return
529 }
530
531 dir.loading = true
532 go func() {
533 nav.dirChan <- newDir(dir.path)
534 }()
535 case dir.dircounts != getDirCounts(dir.path):
536 dir.loading = true
537 go func() {
538 nav.dirChan <- newDir(dir.path)
539 }()
540 // Although toggling dircounts can affect sorting, it is already handled by
541 // reloading the directory which should sort the files anyway, so it is not
542 // checked below.
543 case dir.sortby != getSortBy(dir.path) ||
544 dir.dirfirst != getDirFirst(dir.path) ||
545 dir.dironly != getDirOnly(dir.path) ||
546 dir.hidden != getHidden(dir.path) ||
547 dir.reverse != getReverse(dir.path) ||
548 !slices.Equal(dir.hiddenfiles, gOpts.hiddenfiles) ||
549 dir.sortignorecase != getSortIgnoreCase(dir.path) ||
550 dir.sortignoredia != getSortIgnoreDia(dir.path):
551 dir.loading = true
552 sd := *dir
553 go func() {
554 sd.sort()
555 sd.loading = false
556 nav.dirChan <- &sd
557 }()
558 }
559 }
560
561 func (nav *nav) loadDirs(wd string) {
562 var dirPaths []string
563
564 for curr, base := wd, ""; !isRoot(base); curr, base = filepath.Dir(curr), filepath.Base(curr) {
565 dirPaths = append(dirPaths, curr)
566
567 dir := nav.getDir(curr)
568 if base != "" {
569 dir.sel(base, nav.height)
570 }
571 }
572
573 slices.Reverse(dirPaths)
574 nav.dirPaths = dirPaths
575 }
576
577 func newNav(ui *ui) *nav {
578 nav := &nav{
579 copyJobsChan: make(chan int, 1024),
580 copyBytesChan: make(chan int64, 1024),
581 copyTotalChan: make(chan int64, 1024),
582 moveCountChan: make(chan int, 1024),
583 moveTotalChan: make(chan int, 1024),
584 deleteCountChan: make(chan int, 1024),
585 deleteTotalChan: make(chan int, 1024),
586 preloadChan: make(chan string, 1024),
587 previewChan: make(chan string, 1024),
588 dirChan: make(chan *dir),
589 regChan: make(chan *reg),
590 fileChan: make(chan *file),
591 delChan: make(chan string),
592 dirCache: make(map[string]*dir),
593 regCache: make(map[string]*reg),
594 marks: make(map[string]string),
595 selections: make(map[string]int),
596 tags: make(map[string]string),
597 selectionInd: 0,
598 previewTimer: time.NewTimer(0),
599 preloadTimer: time.NewTimer(0),
600 jumpList: make([]string, 0),
601 jumpListInd: -1,
602 }
603
604 nav.resize(ui)
605 return nav
606 }
607
608 func (nav *nav) addJumpList() {
609 currPath := nav.currDir().path
610 if nav.jumpListInd >= 0 && nav.jumpListInd < len(nav.jumpList)-1 {
611 if nav.jumpList[nav.jumpListInd] == currPath {
612 // walking the jumpList
613 return
614 }
615 nav.jumpList = nav.jumpList[:nav.jumpListInd+1]
616 }
617 if len(nav.jumpList) == 0 || nav.jumpList[len(nav.jumpList)-1] != currPath {
618 nav.jumpList = append(nav.jumpList, currPath)
619 }
620 nav.jumpListInd = len(nav.jumpList) - 1
621 }
622
623 func (nav *nav) cdJumpListPrev() {
624 if nav.jumpListInd > 0 {
625 nav.jumpListInd--
626 if err := nav.cd(nav.jumpList[nav.jumpListInd]); err != nil {
627 log.Print(err)
628 }
629 }
630 }
631
632 func (nav *nav) cdJumpListNext() {
633 if nav.jumpListInd < len(nav.jumpList)-1 {
634 nav.jumpListInd++
635 if err := nav.cd(nav.jumpList[nav.jumpListInd]); err != nil {
636 log.Print(err)
637 }
638 }
639 }
640
641 func (nav *nav) renew() {
642 for _, path := range nav.dirPaths {
643 dir := nav.getDir(path)
644 nav.checkDir(dir)
645 }
646
647 for m := range nav.selections {
648 if _, err := os.Lstat(m); os.IsNotExist(err) {
649 delete(nav.selections, m)
650 }
651 }
652
653 if len(nav.selections) == 0 {
654 nav.selectionInd = 0
655 }
656 }
657
658 func (nav *nav) reload() {
659 wd := nav.currDir().path
660 curr := nav.currFile()
661
662 clear(nav.dirCache)
663 clear(nav.regCache)
664
665 nav.loadDirs(wd)
666
667 if curr != nil {
668 dir := nav.currDir()
669 dir.files = append(dir.files, curr)
670 }
671 }
672
673 func (nav *nav) resize(ui *ui) {
674 previewWin := ui.wins[len(ui.wins)-1]
675 if previewWin.h == nav.height && previewWin.w == nav.previewWidth {
676 return
677 }
678
679 widthChanged := previewWin.w != nav.previewWidth
680
681 nav.height = previewWin.h
682 nav.previewWidth = previewWin.w
683
684 for _, path := range nav.dirPaths {
685 nav.getDir(path).boundPos(nav.height)
686 }
687
688 if widthChanged {
689 clear(nav.regCache)
690 } else {
691 // drop entries that no longer match the new pane height
692 for path, r := range nav.regCache {
693 if r.loading || r.sixel || (previewWin.h > len(r.lines) && len(r.lines) == r.height) {
694 delete(nav.regCache, path)
695 }
696 }
697 }
698 nav.preloadTimer.Reset(200 * time.Millisecond)
699 }
700
701 func (nav *nav) position() {
702 var base string
703
704 for i, path := range slices.Backward(nav.dirPaths) {
705 if i < len(nav.dirPaths)-1 {
706 nav.getDir(path).sel(base, nav.height)
707 }
708
709 base = filepath.Base(path)
710 }
711 }
712
713 func (nav *nav) exportFiles() {
714 var currFile string
715 if curr := nav.currFile(); curr != nil {
716 currFile = quoteString(curr.path)
717 }
718
719 var selections []string
720 for _, selection := range nav.currSelections() {
721 selections = append(selections, quoteString(selection))
722 }
723 currSelections := strings.Join(selections, gOpts.filesep)
724
725 var vSelections []string
726 for _, selection := range nav.currDir().visualSelections() {
727 vSelections = append(vSelections, quoteString(selection))
728 }
729 currVSelections := strings.Join(vSelections, gOpts.filesep)
730
731 os.Setenv("f", currFile)
732 os.Setenv("fs", currSelections)
733 os.Setenv("fv", currVSelections)
734 os.Setenv("PWD", quoteString(nav.currDir().path))
735
736 if len(selections) == 0 {
737 os.Setenv("fx", currFile)
738 } else {
739 os.Setenv("fx", currSelections)
740 }
741 }
742
743 func (nav *nav) preloadLoop(ui *ui) {
744 stack := []string{}
745
746 push := func(path string) {
747 stack = slices.DeleteFunc(stack, func(s string) bool { return s == path })
748 stack = append(stack, path)
749 }
750
751 pop := func() string {
752 path := stack[len(stack)-1]
753 stack = stack[:len(stack)-1]
754 return path
755 }
756
757 for {
758 if len(stack) == 0 {
759 push(<-nav.preloadChan)
760 } else {
761 select {
762 case path := <-nav.preloadChan:
763 push(path)
764 default:
765 path := pop()
766 nav.preview(path, ui.wins[len(ui.wins)-1], "preload")
767 }
768 }
769 }
770 }
771
772 func (nav *nav) previewLoop(ui *ui) {
773 var prev string
774 for path := range nav.previewChan {
775 isClear := len(path) == 0
776 loop:
777 for {
778 select {
779 case path = <-nav.previewChan:
780 isClear = isClear || len(path) == 0
781 default:
782 break loop
783 }
784 }
785 win := ui.wins[len(ui.wins)-1]
786 if isClear && len(gOpts.previewer) != 0 && len(gOpts.cleaner) != 0 && nav.volatilePreview {
787 cmd := exec.Command(
788 gOpts.cleaner,
789 prev,
790 strconv.Itoa(win.w),
791 strconv.Itoa(win.h),
792 strconv.Itoa(win.x),
793 strconv.Itoa(win.y),
794 path,
795 )
796 var stderr bytes.Buffer
797 cmd.Stderr = &stderr
798
799 if err := cmd.Run(); err != nil {
800 var exitErr *exec.ExitError
801 if !errors.As(err, &exitErr) {
802 log.Printf("cleaning preview: %s", err)
803 }
804 }
805 if s := strings.TrimSpace(stderr.String()); s != "" {
806 s = strings.Join(strings.Fields(s), " ")
807 log.Printf("cleaning preview (stderr): %s", s)
808 }
809 nav.volatilePreview = false
810 }
811 if len(path) != 0 {
812 nav.preview(path, win, "preview")
813 prev = path
814 }
815 }
816 }
817
818 func matchPattern(pattern, name, path string) bool {
819 s := name
820
821 pattern = replaceTilde(pattern)
822
823 if filepath.IsAbs(pattern) {
824 s = filepath.Join(path, name)
825 }
826
827 // pattern errors are checked when 'hiddenfiles' option is set
828 matched, _ := filepath.Match(pattern, s)
829
830 return matched
831 }
832
833 func (nav *nav) preload() {
834 if !gOpts.preview || !gOpts.preload {
835 return
836 }
837
838 dir := nav.currDir()
839 doPreload := func(i int) {
840 if i < 0 || i >= len(dir.files) {
841 return
842 }
843
844 file := dir.files[i]
845 if !file.isPreviewable() {
846 return
847 }
848
849 if _, ok := nav.regCache[file.path]; ok {
850 return
851 }
852
853 nav.regCache[file.path] = &reg{loading: true, loadTime: time.Now(), path: file.path}
854 select {
855 case nav.preloadChan <- file.path:
856 default:
857 }
858 }
859
860 for i := nav.height / 2; i >= 1; i-- {
861 doPreload(dir.ind - i)
862 doPreload(dir.ind + i)
863 }
864 doPreload(dir.ind)
865 }
866
867 func (nav *nav) preview(path string, win *win, mode string) {
868 reg := &reg{loadTime: time.Now(), path: path, height: win.h}
869 defer func() {
870 if (gOpts.preload && mode == "preview") || (!gOpts.preload && reg.volatile) {
871 nav.volatilePreview = true
872 }
873
874 if gOpts.preload == (mode == "preload") {
875 nav.regChan <- reg
876 }
877 }()
878
879 var reader *bufio.Reader
880
881 if len(gOpts.previewer) != 0 {
882 cmd := exec.Command(
883 gOpts.previewer,
884 path,
885 strconv.Itoa(win.w),
886 strconv.Itoa(win.h),
887 strconv.Itoa(win.x),
888 strconv.Itoa(win.y),
889 mode,
890 )
891 var stderr bytes.Buffer
892 cmd.Stderr = &stderr
893
894 out, err := cmd.StdoutPipe()
895 if err != nil {
896 log.Printf("previewing file: %s", err)
897 return
898 }
899
900 if err := cmd.Start(); err != nil {
901 log.Printf("previewing file: %s", err)
902 out.Close()
903 return
904 }
905
906 defer func() {
907 if err := cmd.Wait(); err != nil {
908 var exitErr *exec.ExitError
909 if errors.As(err, &exitErr) {
910 reg.volatile = true
911 } else {
912 log.Printf("loading file: %s", err)
913 }
914 }
915 if s := strings.TrimSpace(stderr.String()); s != "" {
916 s = strings.Join(strings.Fields(s), " ")
917 log.Printf("loading file (stderr): %s", s)
918 }
919 }()
920 defer out.Close()
921 reader = bufio.NewReader(out)
922 } else {
923 lstat, err := os.Lstat(path)
924 if err != nil {
925 log.Printf("lstat: %s", err)
926 return
927 }
928
929 if !lstat.Mode().IsRegular() {
930 return
931 }
932
933 f, err := os.Open(path)
934 if err != nil {
935 log.Printf("opening file: %s", err)
936 return
937 }
938
939 defer f.Close()
940 reader = bufio.NewReader(f)
941 }
942
943 lines, binary, sixel := readLines(reader, win.h)
944 if binary {
945 lines = []string{"\033[7mbinary\033[0m"}
946 }
947
948 // The internal previewer reads raw file content which may contain
949 // escape sequences that corrupt the display or enable code execution
950 // (e.g. OSC 52 clipboard writes). Replace control characters with
951 // U+FFFD so they are visible but cannot form escape sequences.
952 if len(gOpts.previewer) == 0 && !binary {
953 sixel = false
954 for i, l := range lines {
955 lines[i] = sanitizePreview(l)
956 }
957 }
958
959 reg.lines = lines
960 reg.sixel = sixel
961 }
962
963 func (nav *nav) loadReg(path string, volatile bool) *reg {
964 r, ok := nav.regCache[path]
965 if !ok || (!gOpts.preload && r.loading) {
966 r = &reg{loading: true, loadTime: time.Now(), path: path}
967 nav.regCache[path] = r
968 if gOpts.preload {
969 select {
970 case nav.preloadChan <- path:
971 default:
972 }
973 } else {
974 nav.previewChan <- path
975 }
976 return r
977 }
978
979 if volatile && r.volatile {
980 if !gOpts.preload {
981 r.loadTime = time.Now()
982 r.loading = true
983 }
984 nav.previewChan <- path
985 }
986
987 nav.checkReg(r)
988 return r
989 }
990
991 func (nav *nav) checkReg(reg *reg) {
992 s, err := os.Stat(reg.path)
993 if err != nil {
994 return
995 }
996
997 now := time.Now()
998
999 // XXX: Linux builtin exFAT drivers are able to predict modifications in the future
1000 // https://bugs.launchpad.net/ubuntu/+source/ubuntu-meta/+bug/1872504
1001 if s.ModTime().After(now) {
1002 return
1003 }
1004
1005 if s.ModTime().After(reg.loadTime) {
1006 reg.loadTime = now
1007 reg.loading = true
1008 if gOpts.preload {
1009 select {
1010 case nav.preloadChan <- reg.path:
1011 default:
1012 }
1013 } else {
1014 nav.previewChan <- reg.path
1015 }
1016 }
1017 }
1018
1019 func (nav *nav) sort() {
1020 for _, path := range nav.dirPaths {
1021 dir := nav.getDir(path)
1022 name := dir.name()
1023 dir.sort()
1024 dir.sel(name, nav.height)
1025 }
1026
1027 if curr := nav.currFile(); curr != nil && curr.IsDir() {
1028 dir := nav.getDir(curr.path)
1029 name := dir.name()
1030 dir.sort()
1031 dir.sel(name, nav.height)
1032 }
1033 }
1034
1035 func (nav *nav) setFilter(filter []string) error {
1036 newfilter := []string{}
1037 for _, tok := range filter {
1038 if tok == "" {
1039 continue
1040 }
1041
1042 // check if filter is valid by applying it to a dummy string
1043 if _, err := searchMatch("a", strings.TrimPrefix(tok, "!"), gOpts.filtermethod); err != nil {
1044 return err
1045 }
1046
1047 newfilter = append(newfilter, tok)
1048 }
1049
1050 dir := nav.currDir()
1051 dir.filter = newfilter
1052
1053 // Apply filter, by sorting current dir (see nav.sort())
1054 name := dir.name()
1055 dir.sort()
1056 dir.sel(name, nav.height)
1057 return nil
1058 }
1059
1060 func (nav *nav) up(dist int) bool {
1061 dir := nav.currDir()
1062
1063 old := dir.ind
1064
1065 if dir.ind == 0 {
1066 if gOpts.wrapscroll {
1067 nav.bottom()
1068 dir.visualWrap--
1069 }
1070 return old != dir.ind
1071 }
1072
1073 dir.ind -= dist
1074 dir.ind = max(0, dir.ind)
1075
1076 dir.pos -= dist
1077 dir.boundPos(nav.height)
1078
1079 return old != dir.ind
1080 }
1081
1082 func (nav *nav) down(dist int) bool {
1083 dir := nav.currDir()
1084
1085 old := dir.ind
1086
1087 maxind := len(dir.files) - 1
1088
1089 if dir.ind >= maxind {
1090 if gOpts.wrapscroll {
1091 nav.top()
1092 dir.visualWrap++
1093 }
1094 return old != dir.ind
1095 }
1096
1097 dir.ind += dist
1098 dir.ind = min(maxind, dir.ind)
1099
1100 dir.pos += dist
1101 dir.boundPos(nav.height)
1102
1103 return old != dir.ind
1104 }
1105
1106 func (nav *nav) scrollUp(dist int) bool {
1107 dir := nav.currDir()
1108
1109 old := dir.ind
1110
1111 oldPos := dir.pos
1112 dir.pos += dist
1113 dir.boundPos(nav.height)
1114
1115 dir.ind -= dist - (dir.pos - oldPos)
1116 dir.ind = max(dir.ind, dir.pos)
1117
1118 return old != dir.ind
1119 }
1120
1121 func (nav *nav) scrollDown(dist int) bool {
1122 dir := nav.currDir()
1123
1124 old := dir.ind
1125
1126 oldPos := dir.pos
1127 dir.pos -= dist
1128 dir.boundPos(nav.height)
1129
1130 dir.ind += dist - (oldPos - dir.pos)
1131 dir.ind = min(dir.ind, dir.pos+max(len(dir.files)-nav.height, 0))
1132
1133 return old != dir.ind
1134 }
1135
1136 func (nav *nav) updir() error {
1137 if len(nav.dirPaths) < 2 {
1138 return nil
1139 }
1140
1141 if err := os.Chdir(nav.dirPaths[len(nav.dirPaths)-2]); err != nil {
1142 return fmt.Errorf("updir: %w", err)
1143 }
1144
1145 nav.dirPaths = nav.dirPaths[:len(nav.dirPaths)-1]
1146 return nil
1147 }
1148
1149 func (nav *nav) open() error {
1150 curr := nav.currFile()
1151 if curr == nil {
1152 return nil
1153 }
1154
1155 if err := os.Chdir(curr.path); err != nil {
1156 return fmt.Errorf("open: %w", err)
1157 }
1158
1159 nav.dirPaths = append(nav.dirPaths, curr.path)
1160 return nil
1161 }
1162
1163 func (nav *nav) top() bool {
1164 dir := nav.currDir()
1165
1166 old := dir.ind
1167
1168 dir.ind = 0
1169 dir.pos = 0
1170
1171 return old != dir.ind
1172 }
1173
1174 func (nav *nav) bottom() bool {
1175 dir := nav.currDir()
1176
1177 old := dir.ind
1178
1179 dir.ind = max(len(dir.files)-1, 0)
1180 dir.pos = min(dir.ind, nav.height-1)
1181
1182 return old != dir.ind
1183 }
1184
1185 func (nav *nav) high() bool {
1186 dir := nav.currDir()
1187
1188 old := dir.ind
1189 beg := max(dir.ind-dir.pos, 0)
1190 offs := min(nav.height/2, gOpts.scrolloff)
1191 if beg == 0 {
1192 offs = 0
1193 }
1194
1195 dir.ind = beg + offs
1196 dir.pos = offs
1197
1198 return old != dir.ind
1199 }
1200
1201 func (nav *nav) middle() bool {
1202 dir := nav.currDir()
1203
1204 old := dir.ind
1205 beg := max(dir.ind-dir.pos, 0)
1206 end := min(beg+nav.height, len(dir.files))
1207
1208 half := (end - beg) / 2
1209 dir.ind = beg + half
1210 dir.pos = half
1211
1212 return old != dir.ind
1213 }
1214
1215 func (nav *nav) low() bool {
1216 dir := nav.currDir()
1217
1218 old := dir.ind
1219 beg := max(dir.ind-dir.pos, 0)
1220 end := min(beg+nav.height, len(dir.files))
1221
1222 offs := min(nav.height/2, gOpts.scrolloff)
1223 // use a smaller value for half when the height is even and scrolloff is
1224 // maxed in order to stay at the same row when using both high and low
1225 if nav.height%2 == 0 {
1226 offs = min(nav.height/2-1, gOpts.scrolloff)
1227 }
1228
1229 if end == len(dir.files) {
1230 offs = 0
1231 }
1232
1233 dir.ind = end - 1 - offs
1234 dir.pos = end - beg - 1 - offs
1235
1236 return old != dir.ind
1237 }
1238
1239 func (nav *nav) move(index int) bool {
1240 old := nav.currDir().ind
1241
1242 switch {
1243 case index < old:
1244 return nav.up(old - index)
1245 case index > old:
1246 return nav.down(index - old)
1247 default:
1248 return false
1249 }
1250 }
1251
1252 func (nav *nav) toggleSelection(path string) {
1253 if _, ok := nav.selections[path]; ok {
1254 delete(nav.selections, path)
1255 if len(nav.selections) == 0 {
1256 nav.selectionInd = 0
1257 }
1258 } else {
1259 nav.selections[path] = nav.selectionInd
1260 nav.selectionInd++
1261 }
1262 }
1263
1264 func (nav *nav) toggle() {
1265 if curr := nav.currFile(); curr != nil {
1266 nav.toggleSelection(curr.path)
1267 }
1268 }
1269
1270 func (nav *nav) tagToggleSelection(path, tag string) {
1271 if _, ok := nav.tags[path]; ok {
1272 delete(nav.tags, path)
1273 } else {
1274 nav.tags[path] = tag
1275 }
1276 }
1277
1278 func (nav *nav) tagToggle(tag string) error {
1279 list, err := nav.currFileOrSelections()
1280 if err != nil {
1281 return err
1282 }
1283
1284 if printLength(tag) != 1 {
1285 return errors.New("tag should be single width character")
1286 }
1287
1288 for _, path := range list {
1289 nav.tagToggleSelection(path, tag)
1290 }
1291
1292 return nil
1293 }
1294
1295 func (nav *nav) tag(tag string) error {
1296 list, err := nav.currFileOrSelections()
1297 if err != nil {
1298 return err
1299 }
1300
1301 if printLength(tag) != 1 {
1302 return errors.New("tag should be single width character")
1303 }
1304
1305 for _, path := range list {
1306 nav.tags[path] = tag
1307 }
1308
1309 return nil
1310 }
1311
1312 func (nav *nav) invert() {
1313 for _, file := range nav.currDir().files {
1314 nav.toggleSelection(file.path)
1315 }
1316 }
1317
1318 func (nav *nav) unselect() {
1319 clear(nav.selections)
1320 nav.selectionInd = 0
1321 }
1322
1323 func (nav *nav) save(mode clipboardMode) error {
1324 list, err := nav.currFileOrSelections()
1325 if err != nil {
1326 return err
1327 }
1328
1329 clipboard := clipboard{list, mode}
1330 if err := saveFiles(clipboard); err != nil {
1331 return err
1332 }
1333
1334 nav.clipboard = clipboard
1335 return nil
1336 }
1337
1338 func (nav *nav) copyAsync(app *app, srcs []string, dstDir string) {
1339 errCount := 0
1340 sendErr := func(format string, a ...any) {
1341 errCount++
1342 msg := fmt.Sprintf("copy [%d]: %s", errCount, fmt.Sprintf(format, a...))
1343 app.ui.exprChan <- &callExpr{"echoerr", []string{msg}, 1}
1344 }
1345
1346 _, err := os.Stat(dstDir)
1347 if os.IsNotExist(err) {
1348 sendErr("%v", err)
1349 return
1350 }
1351
1352 // Indicate that a copy operation is in progress. Using the total bytes to
1353 // determine this instead will mean that it is possible for copySize to take
1354 // a while, but not be reflected in the UI until it has finished.
1355 nav.copyJobsChan <- 1
1356
1357 total, err := copySize(srcs)
1358 if err != nil {
1359 sendErr("%v", err)
1360 nav.copyJobsChan <- -1
1361 return
1362 }
1363
1364 nav.copyTotalChan <- total
1365
1366 nums, errs := copyAll(srcs, dstDir, gOpts.preserve)
1367
1368 loop:
1369 for {
1370 select {
1371 case n := <-nums:
1372 nav.copyBytesChan <- n
1373 case err, ok := <-errs:
1374 if !ok {
1375 break loop
1376 }
1377 sendErr("%v", err)
1378 }
1379 }
1380
1381 nav.copyJobsChan <- -1
1382 nav.copyTotalChan <- -total
1383
1384 if gSingleMode {
1385 nav.renew()
1386 app.ui.loadFile(app, true)
1387 } else {
1388 if _, err := remote("send load"); err != nil {
1389 sendErr("%v", err)
1390 }
1391 }
1392
1393 if errCount == 0 {
1394 app.ui.exprChan <- &callExpr{"echo", []string{"\033[0;32mCopied successfully\033[0m"}, 1}
1395 }
1396 }
1397
1398 func (nav *nav) moveAsync(app *app, srcs []string, dstDir string) {
1399 errCount := 0
1400 sendErr := func(format string, a ...any) {
1401 errCount++
1402 msg := fmt.Sprintf("move [%d]: %s", errCount, fmt.Sprintf(format, a...))
1403 app.ui.exprChan <- &callExpr{"echoerr", []string{msg}, 1}
1404 }
1405
1406 _, err := os.Stat(dstDir)
1407 if os.IsNotExist(err) {
1408 sendErr("%v", err)
1409 return
1410 }
1411
1412 nav.moveTotalChan <- len(srcs)
1413
1414 for _, src := range srcs {
1415 nav.moveCountChan <- 1
1416
1417 srcStat, err := os.Lstat(src)
1418 if err != nil {
1419 sendErr("%v", err)
1420 continue
1421 }
1422
1423 file := filepath.Base(src)
1424 dst := filepath.Join(dstDir, file)
1425
1426 if dstStat, err := os.Lstat(dst); err == nil {
1427 if os.SameFile(srcStat, dstStat) {
1428 sendErr("rename %s %s: source and destination are the same file", src, dst)
1429 continue
1430 }
1431 ext := getFileExtension(dstStat)
1432 basename := file[:len(file)-len(ext)]
1433 var newPath string
1434 for i := 1; !os.IsNotExist(err); i++ {
1435 file = strings.ReplaceAll(gOpts.dupfilefmt, "%f", basename+ext)
1436 file = strings.ReplaceAll(file, "%b", basename)
1437 file = strings.ReplaceAll(file, "%e", ext)
1438 file = strings.ReplaceAll(file, "%n", strconv.Itoa(i))
1439 newPath = filepath.Join(dstDir, file)
1440 _, err = os.Lstat(newPath)
1441 }
1442 dst = newPath
1443 }
1444
1445 if err := os.Rename(src, dst); err != nil {
1446 if errCrossDevice(err) {
1447 nav.copyJobsChan <- 1
1448
1449 total, err := copySize([]string{src})
1450 if err != nil {
1451 sendErr("%v", err)
1452 nav.copyJobsChan <- -1
1453 continue
1454 }
1455
1456 nav.copyTotalChan <- total
1457
1458 nums, errs := copyAll([]string{src}, dstDir, []string{"mode", "timestamps"})
1459
1460 oldCount := errCount
1461 loop:
1462 for {
1463 select {
1464 case n := <-nums:
1465 nav.copyBytesChan <- n
1466 case err, ok := <-errs:
1467 if !ok {
1468 break loop
1469 }
1470 sendErr("%v", err)
1471 }
1472 }
1473
1474 nav.copyJobsChan <- -1
1475 nav.copyTotalChan <- -total
1476
1477 if errCount == oldCount {
1478 if err := os.RemoveAll(src); err != nil {
1479 sendErr("%v", err)
1480 }
1481 }
1482 } else {
1483 sendErr("%v", err)
1484 }
1485 }
1486 }
1487
1488 nav.moveTotalChan <- -len(srcs)
1489
1490 if gSingleMode {
1491 nav.renew()
1492 app.ui.loadFile(app, true)
1493 } else {
1494 if _, err := remote("send load"); err != nil {
1495 sendErr("%v", err)
1496 }
1497 }
1498
1499 if errCount == 0 {
1500 app.ui.exprChan <- &callExpr{"clear", nil, 1}
1501 app.ui.exprChan <- &callExpr{"echo", []string{"\033[0;32mMoved successfully\033[0m"}, 1}
1502 }
1503 }
1504
1505 func (nav *nav) paste(app *app) error {
1506 clipboard, err := loadFiles()
1507 if err != nil {
1508 return err
1509 }
1510
1511 if len(clipboard.paths) == 0 {
1512 return errors.New("no files in clipboard")
1513 }
1514
1515 dstDir := nav.currDir().path
1516
1517 if clipboard.mode == clipboardCopy {
1518 go nav.copyAsync(app, clipboard.paths, dstDir)
1519 } else {
1520 go nav.moveAsync(app, clipboard.paths, dstDir)
1521 }
1522
1523 return nil
1524 }
1525
1526 func (nav *nav) del(app *app) error {
1527 list, err := nav.currFileOrSelections()
1528 if err != nil {
1529 return err
1530 }
1531
1532 go func() {
1533 echo := &callExpr{"echoerr", []string{""}, 1}
1534 errCount := 0
1535
1536 nav.deleteTotalChan <- len(list)
1537
1538 for _, path := range list {
1539 nav.deleteCountChan <- 1
1540
1541 if err := os.RemoveAll(path); err != nil {
1542 errCount++
1543 echo.args[0] = fmt.Sprintf("[%d] %s", errCount, err)
1544 app.ui.exprChan <- echo
1545 }
1546 }
1547
1548 nav.deleteTotalChan <- -len(list)
1549
1550 if gSingleMode {
1551 nav.renew()
1552 app.ui.loadFile(app, true)
1553 } else {
1554 if _, err := remote("send load"); err != nil {
1555 errCount++
1556 echo.args[0] = fmt.Sprintf("[%d] %s", errCount, err)
1557 app.ui.exprChan <- echo
1558 }
1559 }
1560 }()
1561
1562 return nil
1563 }
1564
1565 func (nav *nav) rename() error {
1566 oldPath := nav.renameOldPath
1567 newPath := nav.renameNewPath
1568
1569 if err := os.Rename(oldPath, newPath); err != nil {
1570 return err
1571 }
1572
1573 lstat, err := os.Lstat(newPath)
1574 if err != nil {
1575 return err
1576 }
1577
1578 // It is possible for newPath to already have cache entries if it previously
1579 // existed and was deleted. In this case the cache entries should be deleted
1580 // before loading newPath to prevent displaying a stale preview. However,
1581 // this clears only the current instance of lf, and not any other instances.
1582 deletePathRecursive(nav.regCache, newPath)
1583 deletePathRecursive(nav.dirCache, newPath)
1584 dir := nav.getDir(filepath.Dir(newPath))
1585 nav.checkDir(dir)
1586
1587 if dir.loading {
1588 for i := range dir.allFiles {
1589 if dir.allFiles[i].path == oldPath {
1590 dir.allFiles[i] = &file{FileInfo: lstat}
1591 break
1592 }
1593 }
1594 dir.sort()
1595 }
1596
1597 dir.sel(lstat.Name(), nav.height)
1598
1599 return nil
1600 }
1601
1602 func (nav *nav) sync() error {
1603 clipboard, err := loadFiles()
1604 if err != nil {
1605 return err
1606 }
1607
1608 nav.clipboard = clipboard
1609
1610 tempmarks := make(map[string]string)
1611 for _, ch := range gOpts.tempmarks {
1612 k := string(ch)
1613 if v, ok := nav.marks[k]; ok {
1614 tempmarks[k] = v
1615 }
1616 }
1617 errMarks := nav.readMarks()
1618 maps.Copy(nav.marks, tempmarks)
1619
1620 err = nav.readTags()
1621
1622 if errMarks != nil {
1623 return errMarks
1624 }
1625 return err
1626 }
1627
1628 func (nav *nav) cd(path string) error {
1629 if err := os.Chdir(path); err != nil {
1630 return err
1631 }
1632
1633 nav.loadDirs(path)
1634 nav.renew()
1635 nav.addJumpList()
1636 return nil
1637 }
1638
1639 func (nav *nav) globSel(pattern string, invert bool) error {
1640 dir := nav.currDir()
1641 anyMatched := false
1642
1643 for i := range dir.files {
1644 matched, err := filepath.Match(pattern, dir.files[i].Name())
1645 if err != nil {
1646 return fmt.Errorf("glob-select: %w", err)
1647 }
1648 if matched {
1649 anyMatched = true
1650 fpath := filepath.Join(dir.path, dir.files[i].Name())
1651 if _, ok := nav.selections[fpath]; ok == invert {
1652 nav.toggleSelection(fpath)
1653 }
1654 }
1655 }
1656
1657 if !anyMatched {
1658 return fmt.Errorf("glob-select: pattern not found: %s", pattern)
1659 }
1660
1661 return nil
1662 }
1663
1664 func findMatch(name, pattern string) bool {
1665 if gOpts.ignorecase {
1666 lpattern := strings.ToLower(pattern)
1667 if !gOpts.smartcase || lpattern == pattern {
1668 pattern = lpattern
1669 name = strings.ToLower(name)
1670 }
1671 }
1672 if gOpts.ignoredia {
1673 lpattern := removeDiacritics(pattern)
1674 if !gOpts.smartdia || lpattern == pattern {
1675 pattern = lpattern
1676 name = removeDiacritics(name)
1677 }
1678 }
1679 if gOpts.anchorfind {
1680 return strings.HasPrefix(name, pattern)
1681 }
1682 return strings.Contains(name, pattern)
1683 }
1684
1685 func (nav *nav) findSingle() int {
1686 count := 0
1687 index := 0
1688 dir := nav.currDir()
1689 for i := range dir.files {
1690 if findMatch(dir.files[i].Name(), nav.find) {
1691 count++
1692 if count > 1 {
1693 return count
1694 }
1695 index = i
1696 }
1697 }
1698 if count == 1 {
1699 if index > dir.ind {
1700 nav.down(index - dir.ind)
1701 } else {
1702 nav.up(dir.ind - index)
1703 }
1704 }
1705 return count
1706 }
1707
1708 func (nav *nav) findNext() (bool, bool) {
1709 dir := nav.currDir()
1710 for i := dir.ind + 1; i < len(dir.files); i++ {
1711 if findMatch(dir.files[i].Name(), nav.find) {
1712 return nav.down(i - dir.ind), true
1713 }
1714 }
1715 if gOpts.wrapscan {
1716 for i := range dir.ind {
1717 if findMatch(dir.files[i].Name(), nav.find) {
1718 dir.visualWrap++
1719 return nav.up(dir.ind - i), true
1720 }
1721 }
1722 }
1723 return false, false
1724 }
1725
1726 func (nav *nav) findPrev() (bool, bool) {
1727 dir := nav.currDir()
1728 for i := dir.ind - 1; i >= 0; i-- {
1729 if findMatch(dir.files[i].Name(), nav.find) {
1730 return nav.up(dir.ind - i), true
1731 }
1732 }
1733 if gOpts.wrapscan {
1734 for i := len(dir.files) - 1; i > dir.ind; i-- {
1735 if findMatch(dir.files[i].Name(), nav.find) {
1736 dir.visualWrap--
1737 return nav.down(i - dir.ind), true
1738 }
1739 }
1740 }
1741 return false, false
1742 }
1743
1744 func searchMatch(name, pattern string, method searchMethod) (matched bool, err error) {
1745 if gOpts.ignorecase {
1746 lpattern := strings.ToLower(pattern)
1747 if !gOpts.smartcase || lpattern == pattern {
1748 pattern = lpattern
1749 name = strings.ToLower(name)
1750 }
1751 }
1752 if gOpts.ignoredia {
1753 lpattern := removeDiacritics(pattern)
1754 if !gOpts.smartdia || lpattern == pattern {
1755 pattern = lpattern
1756 name = removeDiacritics(name)
1757 }
1758 }
1759 switch method {
1760 case textSearch:
1761 return strings.Contains(name, pattern), nil
1762 case globSearch:
1763 return filepath.Match(pattern, name)
1764 case regexSearch:
1765 return regexp.MatchString(pattern, name)
1766 default:
1767 return false, errors.New("searchMatch: invalid searchMethod")
1768 }
1769 }
1770
1771 func (nav *nav) searchNext() (bool, error) {
1772 dir := nav.currDir()
1773 for i := dir.ind + 1; i < len(dir.files); i++ {
1774 if matched, err := searchMatch(dir.files[i].Name(), nav.search, gOpts.searchmethod); err != nil {
1775 return false, err
1776 } else if matched {
1777 return nav.down(i - dir.ind), nil
1778 }
1779 }
1780 if gOpts.wrapscan {
1781 for i := range dir.ind {
1782 if matched, err := searchMatch(dir.files[i].Name(), nav.search, gOpts.searchmethod); err != nil {
1783 return false, err
1784 } else if matched {
1785 dir.visualWrap++
1786 return nav.up(dir.ind - i), nil
1787 }
1788 }
1789 }
1790 return false, nil
1791 }
1792
1793 func (nav *nav) searchPrev() (bool, error) {
1794 dir := nav.currDir()
1795 for i := dir.ind - 1; i >= 0; i-- {
1796 if matched, err := searchMatch(dir.files[i].Name(), nav.search, gOpts.searchmethod); err != nil {
1797 return false, err
1798 } else if matched {
1799 return nav.up(dir.ind - i), nil
1800 }
1801 }
1802 if gOpts.wrapscan {
1803 for i := len(dir.files) - 1; i > dir.ind; i-- {
1804 if matched, err := searchMatch(dir.files[i].Name(), nav.search, gOpts.searchmethod); err != nil {
1805 return false, err
1806 } else if matched {
1807 dir.visualWrap--
1808 return nav.down(i - dir.ind), nil
1809 }
1810 }
1811 }
1812 return false, nil
1813 }
1814
1815 func isFiltered(f os.FileInfo, filter []string) bool {
1816 for _, pattern := range filter {
1817 matched, err := searchMatch(f.Name(), strings.TrimPrefix(pattern, "!"), gOpts.filtermethod)
1818 if err != nil {
1819 log.Printf("Filter Error: %s", err)
1820 return false
1821 }
1822 if strings.HasPrefix(pattern, "!") && matched {
1823 return true
1824 } else if !strings.HasPrefix(pattern, "!") && !matched {
1825 return true
1826 }
1827 }
1828 return false
1829 }
1830
1831 func (nav *nav) removeMark(mark string) error {
1832 if _, ok := nav.marks[mark]; ok {
1833 delete(nav.marks, mark)
1834 return nil
1835 }
1836 return errors.New("no such mark")
1837 }
1838
1839 func (nav *nav) readMarks() error {
1840 clear(nav.marks)
1841 f, err := os.Open(gMarksPath)
1842 if os.IsNotExist(err) {
1843 return nil
1844 }
1845 if err != nil {
1846 return fmt.Errorf("opening marks file: %w", err)
1847 }
1848 defer f.Close()
1849
1850 scanner := bufio.NewScanner(f)
1851 for scanner.Scan() {
1852 mark, path, found := strings.Cut(scanner.Text(), ":")
1853 if !found {
1854 return fmt.Errorf("invalid marks file entry: %s", scanner.Text())
1855 }
1856 if _, ok := nav.marks[mark]; !ok {
1857 nav.marks[mark] = path
1858 }
1859 }
1860
1861 if err := scanner.Err(); err != nil {
1862 return fmt.Errorf("reading marks file: %w", err)
1863 }
1864
1865 return nil
1866 }
1867
1868 func (nav *nav) writeMarks() error {
1869 if err := os.MkdirAll(filepath.Dir(gMarksPath), 0o700); err != nil {
1870 return fmt.Errorf("creating data directory: %w", err)
1871 }
1872
1873 f, err := os.OpenFile(gMarksPath, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0o600)
1874 if err != nil {
1875 return fmt.Errorf("creating marks file: %w", err)
1876 }
1877 defer f.Close()
1878
1879 for _, k := range slices.Sorted(maps.Keys(nav.marks)) {
1880 if strings.Contains(gOpts.tempmarks, k) {
1881 continue
1882 }
1883 if strings.ContainsAny(nav.marks[k], "\n\r") {
1884 log.Printf("marks: skipping mark '%s' with newline in path: %q", k, nav.marks[k])
1885 continue
1886 }
1887 _, err = fmt.Fprintf(f, "%s:%s\n", k, nav.marks[k])
1888 if err != nil {
1889 return fmt.Errorf("writing marks file: %w", err)
1890 }
1891 }
1892
1893 return nil
1894 }
1895
1896 func (nav *nav) readTags() error {
1897 clear(nav.tags)
1898 f, err := os.Open(gTagsPath)
1899 if os.IsNotExist(err) {
1900 return nil
1901 }
1902 if err != nil {
1903 return fmt.Errorf("opening tags file: %w", err)
1904 }
1905 defer f.Close()
1906
1907 scanner := bufio.NewScanner(f)
1908 for scanner.Scan() {
1909 text := scanner.Text()
1910
1911 ind := strings.LastIndex(text, ":")
1912 if ind == -1 {
1913 return fmt.Errorf("invalid tags file entry: %s", text)
1914 }
1915
1916 path := text[0:ind]
1917 tag := text[ind+1:]
1918 if _, ok := nav.tags[path]; !ok {
1919 nav.tags[path] = tag
1920 }
1921 }
1922
1923 if err := scanner.Err(); err != nil {
1924 return fmt.Errorf("reading tags file: %w", err)
1925 }
1926
1927 return nil
1928 }
1929
1930 func (nav *nav) writeTags() error {
1931 if err := os.MkdirAll(filepath.Dir(gTagsPath), 0o700); err != nil {
1932 return fmt.Errorf("creating data directory: %w", err)
1933 }
1934
1935 f, err := os.OpenFile(gTagsPath, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0o600)
1936 if err != nil {
1937 return fmt.Errorf("creating tags file: %w", err)
1938 }
1939 defer f.Close()
1940
1941 for _, k := range slices.Sorted(maps.Keys(nav.tags)) {
1942 if strings.ContainsAny(k, "\n\r") {
1943 log.Printf("tags: skipping tag with newline in path: %q", k)
1944 continue
1945 }
1946 _, err = fmt.Fprintf(f, "%s:%s\n", k, nav.tags[k])
1947 if err != nil {
1948 return fmt.Errorf("writing tags file: %w", err)
1949 }
1950 }
1951
1952 return nil
1953 }
1954
1955 func (nav *nav) currDir() *dir {
1956 if len(nav.dirPaths) == 0 {
1957 wd, err := os.Getwd()
1958 if err != nil {
1959 log.Printf("getting current directory: %s", err)
1960 }
1961 nav.loadDirs(wd)
1962 }
1963
1964 path := nav.dirPaths[len(nav.dirPaths)-1]
1965 return nav.getDir(path)
1966 }
1967
1968 func (nav *nav) currFile() *file {
1969 dir := nav.currDir()
1970
1971 if len(dir.files) == 0 {
1972 return nil
1973 }
1974
1975 return dir.files[dir.ind]
1976 }
1977
1978 func (nav *nav) currSelections() []string {
1979 currDirOnly := gOpts.selmode == "dir"
1980 currDirPath := ""
1981 if currDirOnly {
1982 // select only from this directory
1983 currDirPath = nav.currDir().path
1984 }
1985
1986 paths := make([]string, 0, len(nav.selections))
1987 for path := range nav.selections {
1988 if !currDirOnly || filepath.Dir(path) == currDirPath {
1989 paths = append(paths, path)
1990 }
1991 }
1992 slices.SortFunc(paths, func(a, b string) int {
1993 return cmp.Compare(nav.selections[a], nav.selections[b])
1994 })
1995 return paths
1996 }
1997
1998 func (nav *nav) currFileOrSelections() ([]string, error) {
1999 if sel := nav.currSelections(); len(sel) > 0 {
2000 return sel, nil
2001 }
2002
2003 if curr := nav.currFile(); curr != nil {
2004 return []string{curr.path}, nil
2005 }
2006
2007 return nil, errors.New("no file selected")
2008 }
2009
2010 func (nav *nav) calcDirSize() error {
2011 calc := func(f *file) error {
2012 if f.IsDir() {
2013 total, err := copySize([]string{f.path})
2014 if err != nil {
2015 return err
2016 }
2017 f.dirSize = total
2018 }
2019 return nil
2020 }
2021
2022 if len(nav.selections) == 0 {
2023 curr := nav.currFile()
2024 if curr == nil {
2025 return errors.New("no file selected")
2026 }
2027 return calc(curr)
2028 }
2029
2030 for sel := range nav.selections {
2031 lstat, err := os.Lstat(sel)
2032 if err != nil || !lstat.IsDir() {
2033 continue
2034 }
2035 path, name := filepath.Dir(sel), filepath.Base(sel)
2036 dir := nav.getDir(path)
2037
2038 for _, f := range dir.files {
2039 if f.Name() == name {
2040 err := calc(f)
2041 if err != nil {
2042 return err
2043 }
2044 break
2045 }
2046 }
2047 }
2048
2049 return nil
2050 }