-
Notifications
You must be signed in to change notification settings - Fork 2
/
fen.go
1432 lines (1161 loc) · 41.4 KB
/
fen.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
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
//lint:file-ignore ST1005 some user-visible messages are stored in error values and thus occasionally require capitalization
import (
"bufio"
"errors"
"fmt"
"log"
"os"
"os/exec"
"path/filepath"
"reflect"
"runtime"
"strconv"
"strings"
"github.com/kivattt/gogitstatus"
"github.com/rivo/tview"
"github.com/yuin/gluamapper"
lua "github.com/yuin/gopher-lua"
)
type Fen struct {
app *tview.Application
wd string // Current working directory
lastWD string
sel string
lastSel string
lastInRepository string
history History
selected map[string]bool
yankSelected map[string]bool
yankType string // "", "copy", "cut"
selectingWithV bool
selectingWithVStartIndex int
selectingWithVEndIndex int
selectedBeforeSelectingWithV map[string]bool
config Config
configPath string // Config path as read by ReadConfig()
fileOperationsHandler FileOperationsHandler
gitStatusHandler GitStatusHandler
helpScreenVisible *bool
librariesScreenVisible *bool
runningGitStatus bool
initializedGitStatus bool // This is for Fini() because the user might have disabled git_status in the options menu
folderFileCountCache map[string]int
topBar *TopBar
bottomBar *BottomBar
leftPane *FilesPane
middlePane *FilesPane
rightPane *FilesPane
showHomePathAsTilde bool
}
// gluamapper lets you use Go variables like "UiBorders", using the name "ui_borders".
// I happen to like this, but since I can't set the "fen" global to the actual Config value,
// we have to define them manually with a new table where I use these struct tags to look up the names
const luaTagName = "lua"
var ConfigKeysByTagNameNotToIncludeInOptionsMenu = []string{
"no_write", // Would be unsafe to allow disabling no-write (always assume fen --no-write is being ran by a bad actor)
"terminal_title", // The push/pop terminal title escape codes don't work properly while fen is running
}
type Config struct {
UiBorders bool `lua:"ui_borders"`
Mouse bool `lua:"mouse"`
NoWrite bool `lua:"no_write"`
HiddenFiles bool `lua:"hidden_files"`
FoldersFirst bool `lua:"folders_first"`
SplitHomeEnd bool `lua:"split_home_end"`
PrintPathOnOpen bool `lua:"print_path_on_open"`
TerminalTitle bool `lua:"terminal_title"`
ShowHelpText bool `lua:"show_help_text"`
ShowHostname bool `lua:"show_hostname"`
Open []PreviewOrOpenEntry `lua:"open"`
Preview []PreviewOrOpenEntry `lua:"preview"`
SortBy string `lua:"sort_by"`
SortReverse bool `lua:"sort_reverse"`
FileEventIntervalMillis int `lua:"file_event_interval_ms"`
AlwaysShowInfoNumbers bool `lua:"always_show_info_numbers"`
ScrollSpeed int `lua:"scroll_speed"`
Bookmarks [10]string `lua:"bookmarks"`
GitStatus bool `lua:"git_status"`
PreviewSafetyBlocklist bool `lua:"preview_safety_blocklist"`
CloseOnEscape bool `lua:"close_on_escape"`
FileSizeInAllPanes bool `lua:"file_size_in_all_panes"`
}
func NewConfigDefaultValues() Config {
// Anything not specified here will have the default value for its type, e.g. false for booleans
return Config{
Mouse: true,
FoldersFirst: true,
TerminalTitle: true,
ShowHelpText: true,
ShowHostname: true,
SortBy: SORT_ALPHABETICAL,
FileEventIntervalMillis: 300,
ScrollSpeed: 2,
PreviewSafetyBlocklist: true,
}
}
const (
// SORT_NONE should only be used if fen is too slow loading big folders, because it messes with some things
SORT_NONE = "none" // TODO: Make SORT_NONE also disable the implicit sorting of os.ReadDir()
SORT_ALPHABETICAL = "alphabetical"
SORT_MODIFIED = "modified"
SORT_SIZE = "size"
SORT_FILE_EXTENSION = "file-extension"
)
var ValidSortByValues = [...]string{SORT_NONE, SORT_ALPHABETICAL, SORT_MODIFIED, SORT_SIZE, SORT_FILE_EXTENSION}
// To prevent previewing sensitive files
var DefaultPreviewBlocklistCaseInsensitive = []string{
// Filezilla passwords
"sitemanager.xml",
"filezilla.xml",
// Other
".gitconfig",
".bash_history",
".python_history",
// Tokens
".env",
// Possible private keys
"*.key",
".Xauthority",
"*.p12",
"*.pfx",
"*.pkcs12",
"*.pri",
"*.cer",
"*.der",
"*.pem",
"*.p7a",
"*.p7b",
"*.p7c",
"*.p7r",
"*.spc",
"*.p8",
// Reaper license key
"*.rk",
// Databases
"*.db",
"*.accdb",
"*.mdb",
"*.mdf",
"*.sqlite*",
"*.bak",
// Dataset
"*.parquet",
}
type PreviewOrOpenEntry struct {
Script string
Program []string // The name used to be "Programs", but this makes more sense for the lua configuration
Match []string
DoNotMatch []string
}
type PanePos int
const (
LeftPane PanePos = iota
MiddlePane
RightPane
)
func (fen *Fen) Init(path string, app *tview.Application, helpScreenVisible *bool, librariesScreenVisible *bool) error {
fen.app = app
fen.fileOperationsHandler = FileOperationsHandler{fen: fen}
fen.folderFileCountCache = make(map[string]int)
if fen.config.GitStatus {
fen.gitStatusHandler = GitStatusHandler{app: app, fen: fen}
fen.gitStatusHandler.Init()
fen.initializedGitStatus = true
}
fen.helpScreenVisible = helpScreenVisible
fen.librariesScreenVisible = librariesScreenVisible
fen.showHomePathAsTilde = true
if fen.selected == nil {
fen.selected = map[string]bool{}
}
fen.yankSelected = map[string]bool{}
fen.selectedBeforeSelectingWithV = map[string]bool{}
fen.wd = path
fen.sel = path // fen.sel has to be set so fen.UpdatePanes() doesn't panic, it's set accordingly when fen.UpdatePanes() completes.
fen.topBar = NewTopBar(fen)
fen.leftPane = NewFilesPane(fen, LeftPane)
fen.middlePane = NewFilesPane(fen, MiddlePane)
fen.rightPane = NewFilesPane(fen, RightPane)
fen.leftPane.Init()
fen.middlePane.Init()
fen.rightPane.Init()
fen.bottomBar = NewBottomBar(fen)
wdFiles, err := os.ReadDir(fen.wd)
shouldSelectSpecifiedFile := false
stat, statErr := os.Stat(fen.wd)
if statErr == nil && !stat.IsDir() {
shouldSelectSpecifiedFile = true
}
// If our working directory doesn't exist, go up a parent until it does
for err != nil {
if filepath.Dir(fen.wd) == fen.wd {
return err
}
fen.wd = filepath.Dir(fen.wd)
wdFiles, err = os.ReadDir(fen.wd)
}
if len(wdFiles) > 0 {
// HACKY: middlePane has to have entries so that GoTop() will work
fen.middlePane.ChangeDir(fen.wd, true)
fen.GoTop(true)
if shouldSelectSpecifiedFile {
fen.sel = path
}
}
fen.history.AddToHistory(fen.sel)
fen.UpdatePanes(false)
return err
}
func (fen *Fen) Fini() {
fen.leftPane.fileWatcher.Close()
fen.middlePane.fileWatcher.Close()
fen.rightPane.fileWatcher.Close()
if fen.initializedGitStatus {
fen.gitStatusHandler.gitIndexFileWatcher.Close()
close(fen.gitStatusHandler.channel)
fen.gitStatusHandler.wg.Wait()
}
}
func (fen *Fen) InvalidateFolderFileCountCache() {
fen.folderFileCountCache = make(map[string]int)
}
func (fen *Fen) PushAndSetTerminalTitle() {
if runtime.GOOS == "linux" {
os.Stderr.WriteString("\x1b[22t") // Push current terminal title
os.Stderr.WriteString("\x1b]0;fen " + version + "\x07") // Set terminal title to "fen <version>"
}
}
func (fen *Fen) PopTerminalTitle() {
if runtime.GOOS == "linux" {
os.Stderr.WriteString("\x1b[23t") // Pop terminal title, sets it back to normal
}
}
func (fen *Fen) ReadConfig(path string) error {
fen.config = NewConfigDefaultValues()
fen.configPath = path
if !strings.HasSuffix(filepath.Base(path), ".lua") {
fmt.Fprintln(os.Stderr, "Warning: Config file "+path+" has no .lua file extension.\nSince v1.3.0, config files can only be Lua.\n")
}
_, err := os.Stat(path)
if err != nil {
oldJSONConfigPath := filepath.Join(filepath.Dir(path), "fenrc.json")
_, err := os.Stat(oldJSONConfigPath)
if err == nil {
return errors.New("Could not find " + path + ", but found " + oldJSONConfigPath + "\nSince v1.3.0, config files can only be Lua.\n")
}
// We don't want to exit if there is no config file
// This should really be checked by the caller...
return nil
}
L := lua.NewState()
defer L.Close()
// This is what we initially pass to config.lua
luaInitialConfigTable := L.NewTable()
defaultConfigReflectTypes := reflect.TypeOf(fen.config)
defaultConfigReflectValues := reflect.ValueOf(fen.config)
for i := 0; i < defaultConfigReflectValues.NumField(); i++ {
fieldName := defaultConfigReflectTypes.Field(i).Tag.Get(luaTagName)
switch defaultConfigReflectValues.Field(i).Kind() {
case reflect.Bool:
fieldValue := defaultConfigReflectValues.Field(i).Bool()
luaInitialConfigTable.RawSetString(fieldName, lua.LBool(fieldValue))
case reflect.Slice: // fen.open and fen.preview are set to empty lists (called a "table" in lua)
luaInitialConfigTable.RawSetString(fieldName, L.NewTable())
}
}
if err == nil {
luaInitialConfigTable.RawSetString("config_path", lua.LString(PathWithEndSeparator(filepath.Dir(fen.configPath))))
}
luaInitialConfigTable.RawSetString("version", lua.LString(version))
luaInitialConfigTable.RawSetString("runtime_os", lua.LString(runtime.GOOS))
userHomeDir, err := os.UserHomeDir()
if err == nil {
luaInitialConfigTable.RawSetString("home_path", lua.LString(PathWithEndSeparator(userHomeDir)))
}
L.SetGlobal("fen", luaInitialConfigTable)
err = L.DoFile(path)
if err != nil {
return err
}
// TODO: Could probably refactor this and make it check via reflection of fen.config
// In the Lua config, referring to variables by their Go name, e.g. "fen.UiBorders" instead of "fen.ui_borders" makes fen
// pick between one or the other (previously set by luaInitialConfigTable) randomly.
// Why? Because Golang maps.
// You can actually still observe this kind of issue by using atleast 2 invalid fen global variable names in your config:
//
// config.lua:
// fen.UiBorders = false
// fen.AnotherOne = false
//
// then, by running fen multiple times you will see the "Invalid fen global variable name: ..." error msg show one of the two randomly
//
// So let's save the user most of this pain and not allow using the original name.
mapper := gluamapper.NewMapper(gluamapper.Option{NameFunc: func(originalName string) string {
newName := gluamapper.ToUpperCamelCase(originalName)
// If ToUpperCamelCase did nothing, it indicates the use of a fen.config Go name instead of the intended Lua name
if originalName == newName {
// Since we unfortunately can't just return err like in ReadConfig(), let's just replicate the behaviour of handling the error from main.go
fmt.Println("Invalid config '" + path + "', exiting")
err := errors.New("Invalid fen global variable name: " + originalName)
log.Fatal(err)
}
return newName
}})
fenGlobal := L.GetGlobal("fen")
fenGlobalAsTablePointer, ok := L.GetGlobal("fen").(*lua.LTable)
if !ok {
return errors.New("Failed to convert \"fen\" (of type " + fenGlobal.Type().String() + ") to a *lua.LTable")
}
err = mapper.Map(fenGlobalAsTablePointer, &fen.config)
if err != nil {
return err
}
return nil
}
func (fen *Fen) ToggleSelectingWithV() {
if !fen.selectingWithV {
fen.EnableSelectingWithV()
} else {
fen.DisableSelectingWithV()
}
}
func (fen *Fen) EnableSelectingWithV() {
if fen.selectingWithV {
return
}
fen.selectingWithV = true
fen.selectingWithVStartIndex = fen.middlePane.selectedEntryIndex
fen.selectingWithVEndIndex = fen.selectingWithVStartIndex
// We have to do this to copy fen.selected, and not a reference to it
fen.selectedBeforeSelectingWithV = make(map[string]bool)
for k, v := range fen.selected {
fen.selectedBeforeSelectingWithV[k] = v
}
}
func (fen *Fen) DisableSelectingWithV() {
if !fen.selectingWithV {
return
}
fen.selectingWithV = false
fen.selectedBeforeSelectingWithV = make(map[string]bool)
}
func (fen *Fen) KeepMiddlePaneSelectionInBounds() {
// I think Load()ing entries multiple times like this could be unsafe, but might realistically be very rare
if fen.middlePane.selectedEntryIndex >= len(fen.middlePane.entries.Load().([]os.DirEntry)) {
if len(fen.middlePane.entries.Load().([]os.DirEntry)) > 0 {
fen.sel = fen.middlePane.GetSelectedEntryFromIndex(len(fen.middlePane.entries.Load().([]os.DirEntry)) - 1)
err := fen.middlePane.SetSelectedEntryFromString(filepath.Base(fen.sel)) // Duplicated from above...
if err != nil {
panic("In KeepSelectionInBounds(): " + err.Error())
}
} else {
fen.middlePane.SetSelectedEntryFromIndex(0)
}
}
}
// forceReadDir is used for making navigation better, like making a new file or folder selects the new path, renaming a file selecting the new path and toggling hidden files
// Since FilterAndSortEntries overwrites filespane entries
func (fen *Fen) UpdatePanes(forceReadDir bool) {
// If working directory is not accessible, go up to the first accessible parent
// FIXME: We need a log we can scroll through
// This bottomBar message would not show up due to the file watcher updating after it has appeared
/*if err != nil {
fen.bottomBar.TemporarilyShowTextInstead(fen.wd + " became non-accessible, moved to a parent")
}*/
if !filepath.IsAbs(fen.sel) {
panic("fen.sel was not an absolute path")
}
// TODO: Preserve last available selection index (so it doesn't reset to the top)
_, err := os.Stat(fen.wd)
for err != nil {
if filepath.Dir(fen.wd) == fen.wd {
panic("Could not find usable parent path")
}
fen.wd = filepath.Dir(fen.wd)
_, err = os.Stat(fen.wd)
}
fen.leftPane.SetBorder(fen.config.UiBorders)
fen.middlePane.SetBorder(fen.config.UiBorders)
fen.rightPane.SetBorder(fen.config.UiBorders)
if fen.wd != fen.lastWD {
// Has to happen before the filespane ChangeDir() calls which will repopulate the cache
fen.InvalidateFolderFileCountCache()
}
defer func() {
fen.lastWD = fen.wd
}()
fen.leftPane.ChangeDir(filepath.Dir(fen.wd), forceReadDir)
fen.middlePane.ChangeDir(fen.wd, forceReadDir)
if filepath.Clean(fen.wd) == filepath.Dir(fen.wd) {
fen.leftPane.entries.Store([]os.DirEntry{})
} else {
fen.leftPane.SetSelectedEntryFromString(filepath.Base(fen.wd))
}
fen.middlePane.SetSelectedEntryFromString(filepath.Base(fen.sel))
fen.KeepMiddlePaneSelectionInBounds()
fen.sel = filepath.Join(fen.wd, fen.middlePane.GetSelectedEntryFromIndex(fen.middlePane.selectedEntryIndex))
fen.rightPane.ChangeDir(fen.sel, forceReadDir)
// Prevents showing 'empty' a second time in rightPane, if middlePane is already showing 'empty'
if len(fen.middlePane.entries.Load().([]os.DirEntry)) <= 0 {
fen.rightPane.parentIsEmptyFolder = false
}
h, err := fen.history.GetHistoryEntryForPath(fen.sel, fen.config.HiddenFiles)
if err != nil {
fen.rightPane.SetSelectedEntryFromIndex(0)
} else {
fen.rightPane.SetSelectedEntryFromString(filepath.Base(h))
fen.KeepMiddlePaneSelectionInBounds()
}
fen.UpdateSelectingWithV()
selStat, selStatErr := os.Lstat(fen.sel)
if selStatErr != nil {
return
}
// Overwrite the cached folder file count for the currently selected folder
// If fen.wd changed, we already invalidated the cache so this isn't needed
if fen.wd == fen.lastWD && selStat.IsDir() {
count, err := FolderFileCount(fen.sel, fen.config.HiddenFiles)
if err == nil {
fen.folderFileCountCache[fen.sel] = count
}
}
if !fen.config.GitStatus {
return
}
defer func() {
fen.lastSel = fen.sel
}()
// If the current Git repository changed or fen.sel is a directory, ask for a git status
if fen.sel != fen.lastSel {
var inRepository string
if selStat.IsDir() {
inRepository, err = fen.gitStatusHandler.TryFindParentGitRepository(fen.sel)
} else {
inRepository, err = fen.gitStatusHandler.TryFindParentGitRepository(fen.wd)
}
if err != nil {
// When we're no longer in a Git repository, set empty so it can ask for a git status next time we enter one
fen.lastInRepository = ""
}
if !selStat.IsDir() && err != nil {
return
}
// Seems like the fsnotify events don't catch up on FreeBSD, need to always trigger a Git status
if selStat.IsDir() || inRepository != fen.lastInRepository || runtime.GOOS == "freebsd" {
fen.TriggerGitStatus() // TODO: Fix redundant os.Lstat() and TryFindParentGitRepository calls...
}
fen.lastInRepository = inRepository
}
}
// Ask the git status handler to run a "git status" at the currently selected path.
// It may choose to ignore the request if for example, it would restart a git status on the same path or fen.git_status is false.
func (fen *Fen) TriggerGitStatus() {
if !fen.config.GitStatus {
return
}
stat, err := os.Lstat(fen.sel)
if err != nil {
return
}
var currentRepository string
if stat.IsDir() {
currentRepository, err = fen.gitStatusHandler.TryFindParentGitRepository(fen.sel)
} else {
currentRepository, err = fen.gitStatusHandler.TryFindParentGitRepository(fen.wd)
}
if err != nil {
return
}
if currentRepository != fen.lastInRepository {
// Remove previous watched path
watchList := fen.gitStatusHandler.gitIndexFileWatcher.WatchList()
if watchList == nil {
return
}
for _, e := range watchList {
fen.gitStatusHandler.gitIndexFileWatcher.Remove(e)
}
// Watch the new path
fen.gitStatusHandler.gitIndexFileWatcher.Add(filepath.Join(currentRepository, ".git"))
}
if err == nil {
if stat.IsDir() {
fen.gitStatusHandler.channel <- fen.sel
} else {
fen.gitStatusHandler.channel <- fen.wd
}
}
}
func (fen *Fen) HideFilepanes() {
fen.leftPane.Invisible = true
fen.middlePane.Invisible = true
fen.rightPane.Invisible = true
}
func (fen *Fen) ShowFilepanes() {
fen.leftPane.Invisible = false
fen.middlePane.Invisible = false
fen.rightPane.Invisible = false
}
func (fen *Fen) RemoveFromSelectedAndYankSelected(path string) {
delete(fen.selected, path)
delete(fen.yankSelected, path)
}
func (fen *Fen) ToggleSelection(filePath string) {
_, exists := fen.selected[filePath]
if exists {
delete(fen.selected, filePath)
return
}
fen.selected[filePath] = true
}
func (fen *Fen) EnableSelection(filePath string) {
if fen.selected == nil {
fen.selected = map[string]bool{}
}
fen.selected[filePath] = true
}
func (fen *Fen) GoLeft() {
// Not sure if this is necessary
if filepath.Dir(fen.wd) == filepath.Clean(fen.wd) {
return
}
fen.sel = fen.wd
fen.wd = filepath.Dir(fen.wd)
fen.DisableSelectingWithV()
}
func (fen *Fen) GoRight(app *tview.Application, openWith string) {
if len(fen.middlePane.entries.Load().([]os.DirEntry)) <= 0 {
return
}
fi, err := os.Stat(fen.sel)
if err != nil {
return
}
if !fi.IsDir() || openWith != "" {
err := OpenFile(fen, app, openWith)
if err != nil {
fen.bottomBar.TemporarilyShowTextInstead(err.Error())
}
return
}
/* rightFiles, _ := os.ReadDir(fen.sel)
if len(rightFiles) <= 0 {
return
}*/
fen.wd = fen.sel
fen.sel, err = fen.history.GetHistoryEntryForPath(fen.wd, fen.config.HiddenFiles)
if err != nil {
fen.sel = filepath.Join(fen.wd, fen.rightPane.GetSelectedEntryFromIndex(0))
}
fen.DisableSelectingWithV()
}
// Returns false if nothing happened (already at the top, would've moved to the same position)
func (fen *Fen) GoUp(numEntries ...int) bool {
if fen.middlePane.selectedEntryIndex <= 0 {
return false
}
numEntriesToMove := 1
if len(numEntries) > 0 {
numEntriesToMove = max(1, numEntries[0])
}
defer func() {
if fen.selectingWithV {
fen.selectingWithVEndIndex = max(0, fen.middlePane.selectedEntryIndex-numEntriesToMove)
}
}()
if fen.middlePane.selectedEntryIndex-numEntriesToMove < 0 {
fen.sel = filepath.Join(fen.wd, fen.middlePane.GetSelectedEntryFromIndex(0))
return true
}
fen.sel = filepath.Join(fen.wd, fen.middlePane.GetSelectedEntryFromIndex(fen.middlePane.selectedEntryIndex-numEntriesToMove))
return true
}
// Returns false if nothing happened (already at the bottom, would've moved to the same position)
func (fen *Fen) GoDown(numEntries ...int) bool {
if fen.middlePane.selectedEntryIndex >= len(fen.middlePane.entries.Load().([]os.DirEntry))-1 {
return false
}
numEntriesToMove := 1
if len(numEntries) > 0 {
numEntriesToMove = max(1, numEntries[0])
}
defer func() {
if fen.selectingWithV {
fen.selectingWithVEndIndex = min(len(fen.middlePane.entries.Load().([]os.DirEntry))-1, fen.middlePane.selectedEntryIndex+numEntriesToMove)
}
}()
if fen.middlePane.selectedEntryIndex+numEntriesToMove >= len(fen.middlePane.entries.Load().([]os.DirEntry)) {
fen.sel = filepath.Join(fen.wd, fen.middlePane.GetSelectedEntryFromIndex(len(fen.middlePane.entries.Load().([]os.DirEntry))-1))
return true
}
fen.sel = filepath.Join(fen.wd, fen.middlePane.GetSelectedEntryFromIndex(fen.middlePane.selectedEntryIndex+numEntriesToMove))
return true
}
// Returns false if nothing happened (already at the top, would've moved to the same position)
// If called as GoTop(true), it will always update fen.sel and return true (used in fen.Init() and fen.GoPath())
func (fen *Fen) GoTop(force ...bool) bool {
if !(len(force) > 0 && force[0]) && fen.middlePane.selectedEntryIndex <= 0 {
return false
}
fen.sel = filepath.Join(fen.wd, fen.middlePane.GetSelectedEntryFromIndex(0))
if fen.selectingWithV {
fen.selectingWithVEndIndex = 0
}
return true
}
func (fen *Fen) GoMiddle() {
fen.sel = filepath.Join(fen.wd, fen.middlePane.GetSelectedEntryFromIndex((len(fen.middlePane.entries.Load().([]os.DirEntry))-1)/2))
if fen.selectingWithV {
fen.selectingWithVEndIndex = (len(fen.middlePane.entries.Load().([]os.DirEntry)) - 1) / 2
}
}
// Returns false if nothing happened (already at the bottom, would've moved to the same position)
func (fen *Fen) GoBottom() bool {
if fen.middlePane.selectedEntryIndex >= len(fen.middlePane.entries.Load().([]os.DirEntry))-1 {
return false
}
fen.sel = filepath.Join(fen.wd, fen.middlePane.GetSelectedEntryFromIndex(len(fen.middlePane.entries.Load().([]os.DirEntry))-1))
if fen.selectingWithV {
fen.selectingWithVEndIndex = len(fen.middlePane.entries.Load().([]os.DirEntry)) - 1
}
return true
}
// Only meant to be used when fen.config.FoldersFirst is true, if not it will panic
// If a folder not at the bottom is selected, go to the bottom folder, otherwise go to the bottom
// Returns false if nothing happened (already at the bottom, where calling fen.GoBottom() would've moved to the same position)
func (fen *Fen) GoBottomFolderOrBottom() bool {
if !fen.config.FoldersFirst {
panic("GoBottomFolderOrBottom() was called with FoldersFirst disabled")
}
stat, err := os.Lstat(fen.sel)
if err != nil {
return true
}
findBottomFolder := func() (int, error) {
for i := fen.middlePane.selectedEntryIndex; i < len(fen.middlePane.entries.Load().([]os.DirEntry)); i++ {
if fen.middlePane.entries.Load().([]os.DirEntry)[i].IsDir() {
continue
}
bottomFolderIndex := fen.middlePane.ClampEntryIndex(max(0, i-1))
if bottomFolderIndex == fen.middlePane.selectedEntryIndex {
return 0, errors.New("Bottom folder already selected")
}
return bottomFolderIndex, nil
}
return 0, errors.New("No folder found")
}
if stat.IsDir() {
bottomFolder, err := findBottomFolder()
if err != nil {
return fen.GoBottom()
}
fen.GoIndex(bottomFolder)
} else {
return fen.GoBottom()
}
return true
}
// Only meant to be used when fen.config.FoldersFirst is true, if not it will panic
// If a file not at the top is selected, go to the top file, otherwise go to the top
// Returns false if nothing happened (already at the top, where calling fen.GoTop() would've moved to the same position)
func (fen *Fen) GoTopFileOrTop() bool {
if !fen.config.FoldersFirst {
panic("GoTopFileOrTop() was called with FoldersFirst disabled")
}
if fen.middlePane.selectedEntryIndex <= 0 {
return false
}
stat, err := os.Lstat(fen.sel)
if err != nil {
return true
}
findTopFile := func() (int, error) {
for i := fen.middlePane.selectedEntryIndex; i >= 0; i-- {
if !fen.middlePane.entries.Load().([]os.DirEntry)[i].IsDir() {
continue
}
topFileIndex := fen.middlePane.ClampEntryIndex(i + 1)
if topFileIndex == fen.middlePane.selectedEntryIndex {
return 0, errors.New("Top file already selected")
}
return topFileIndex, nil
}
return 0, errors.New("No file found")
}
if !stat.IsDir() {
topFile, err := findTopFile()
if err != nil {
return fen.GoTop()
}
fen.GoIndex(topFile)
} else {
return fen.GoTop()
}
return true
}
func (fen *Fen) GoTopScreen() {
fen.sel = filepath.Join(fen.wd, fen.middlePane.GetSelectedEntryFromIndex(fen.middlePane.GetTopScreenEntryIndex()))
if fen.selectingWithV {
fen.selectingWithVEndIndex = fen.middlePane.GetTopScreenEntryIndex()
}
}
func (fen *Fen) GoBottomScreen() {
fen.sel = filepath.Join(fen.wd, fen.middlePane.GetSelectedEntryFromIndex(fen.middlePane.GetBottomScreenEntryIndex()))
if fen.selectingWithV {
fen.selectingWithVEndIndex = fen.middlePane.GetBottomScreenEntryIndex()
}
}
func (fen *Fen) PageUp() {
_, _, _, height := fen.middlePane.Box.GetInnerRect()
height = max(5, height-10) // Padding
fen.sel = filepath.Join(fen.wd, fen.middlePane.GetSelectedEntryFromIndex(max(0, fen.middlePane.selectedEntryIndex-height)))
if fen.selectingWithV {
fen.selectingWithVEndIndex = max(0, fen.middlePane.selectedEntryIndex-height)
}
}
func (fen *Fen) PageDown() {
_, _, _, height := fen.middlePane.Box.GetInnerRect()
height = max(5, height-10) // Padding
fen.sel = filepath.Join(fen.wd, fen.middlePane.GetSelectedEntryFromIndex(min(len(fen.middlePane.entries.Load().([]os.DirEntry))-1, fen.middlePane.selectedEntryIndex+height)))
if fen.selectingWithV {
fen.selectingWithVEndIndex = min(len(fen.middlePane.entries.Load().([]os.DirEntry))-1, fen.middlePane.selectedEntryIndex+height)
}
}
func (fen *Fen) GoSearchFirstMatch(searchTerm string) error {
if searchTerm == "" {
return errors.New("Empty search term")
}
for _, e := range fen.middlePane.entries.Load().([]os.DirEntry) {
if strings.Contains(strings.ToLower(e.Name()), strings.ToLower(searchTerm)) {
fen.sel = filepath.Join(fen.wd, e.Name())
fen.selectingWithVEndIndex = fen.middlePane.GetSelectedIndexFromEntry(e.Name())
return nil
}
}
return errors.New("Nothing found")
}
func (fen *Fen) UpdateSelectingWithV() {
if !fen.selectingWithV {
return
}
fen.selectingWithVStartIndex = min(len(fen.middlePane.entries.Load().([]os.DirEntry))-1, max(0, fen.selectingWithVStartIndex))
fen.selectingWithVEndIndex = min(len(fen.middlePane.entries.Load().([]os.DirEntry))-1, max(0, fen.selectingWithVEndIndex))
minIndex := min(fen.selectingWithVStartIndex, fen.selectingWithVEndIndex)
maxIndex := max(fen.selectingWithVStartIndex, fen.selectingWithVEndIndex)
// We have to do this to copy fen.selectedBeforeSelectingWithV, and not a reference to it
fen.selected = make(map[string]bool)
for k, v := range fen.selectedBeforeSelectingWithV {
fen.selected[k] = v
}
for i := minIndex; i <= maxIndex; i++ {
fen.EnableSelection(fen.middlePane.GetSelectedPathFromIndex(i))
}
}
func (fen *Fen) GoBookmark(bookmarkNumber int) error {
if bookmarkNumber < 0 || bookmarkNumber > 9 {
panic("Invalid bookmark number")
}
// This is so that pressing '0' uses the 10th bookmark index from config.lua
if bookmarkNumber == 0 {
bookmarkNumber = 9
} else {
bookmarkNumber--
}
path := fen.config.Bookmarks[bookmarkNumber]
if path == "" {
return errors.New("No path configured for bookmark " + strconv.Itoa(bookmarkNumber+1))
}
pathMovedTo, err := fen.GoPath(path)
if err != nil {
return err
}
fen.DisableSelectingWithV()
fen.bottomBar.TemporarilyShowTextInstead("Moved to bookmark: \"" + pathMovedTo + "\"")
return nil
}
func (fen *Fen) GoIndex(index int) {
clampedIndex := fen.middlePane.ClampEntryIndex(index)
fen.sel = filepath.Join(fen.wd, fen.middlePane.GetSelectedEntryFromIndex(clampedIndex))
if fen.selectingWithV {
fen.selectingWithVEndIndex = clampedIndex
}
}
// Returns the absolute path that was moved to, unless there is an error.
// On completion, it always adds fen.sel to the history.
// Implicitly calls fen.UpdatePanes(false) when no error.
func (fen *Fen) GoPath(path string) (string, error) {
// TODO: Add an option to not enter directories
/* PLUGINS:
* We should fen.UpdatePanes(true) when we can't find the newPath in the current middlePane (for going to path on renaming)
* This would slow down "Goto path" when going to a non-existent path, but would guarantee this function always works predictably
* so that Lua plugins won't have to manually call fen.UpdatePanes(true) before a fen.GoPath() for recently renamed/created/etc. files
*/
if path == "" {
return "", errors.New("Empty path provided")
}
pathToUse := filepath.Clean(path)
if !filepath.IsAbs(pathToUse) {
var err error
pathToUse, err = filepath.Abs(filepath.Join(fen.wd, pathToUse))
if err != nil {
return "", err
}
}
stat, err := os.Lstat(pathToUse)