-
-
Notifications
You must be signed in to change notification settings - Fork 4
/
exec.go
1728 lines (1541 loc) · 40 KB
/
exec.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
import (
"bytes"
"fmt"
"os"
"path/filepath"
"regexp"
"runtime"
"runtime/debug"
"sort"
"strconv"
"strings"
"text/tabwriter"
"time"
"github.com/aarzilli/yacco/buf"
"github.com/aarzilli/yacco/clipboard"
"github.com/aarzilli/yacco/config"
"github.com/aarzilli/yacco/edit"
"github.com/aarzilli/yacco/lsp"
"github.com/aarzilli/yacco/modal"
"github.com/aarzilli/yacco/textframe"
"github.com/aarzilli/yacco/util"
)
type ExecContext struct {
col *Col
ed *Editor
br func()
fr *textframe.Frame
buf *buf.Buffer
eventChan chan string
dir string
norefresh bool
}
type CompiledCmd struct {
Str string
F func(ec ExecContext)
}
var KeyBindings = map[string]CompiledCmd{}
type CmdFn func(ec ExecContext, arg string)
type Cmd struct {
Category string
Doc string
Cmd CmdFn
}
var cmds = map[string]Cmd{}
var macros = map[string]CmdFn{}
var spacesRe = regexp.MustCompile("\\s+")
var exitConfirmed = false
func init() {
cmds["Cut"] = Cmd{"Clipboard", "", func(ec ExecContext, arg string) { CopyCmd(ec, arg, true) }}
cmds["Get"] = Cmd{"Files", "", GetCmd}
cmds["Del"] = Cmd{"Frames and Columns", "", func(ec ExecContext, arg string) { DelCmd(ec, arg, false) }}
cmds["Delcol"] = Cmd{"Frames and Columns", "", DelcolCmd}
cmds["Delete"] = Cmd{"Frames and Columns", "Like Del but can not be blocked by an attached process", func(ec ExecContext, arg string) { DelCmd(ec, arg, true) }}
cmds["Dump"] = Cmd{"Session", "[<name>]\tStarts saving session to <name>", DumpCmd}
cmds["Edit"] = Cmd{"Editing", "<...>\tRuns sed-like editing commands, see Help Edit", EditCmd}
cmds["Exit"] = Cmd{"Files", "", ExitCmd}
cmds["Kill"] = Cmd{"Jobs", "[<jobnum>]\tKill all jobs (or the one specified)", KillCmd}
cmds["Setenv"] = Cmd{"Jobs", "<var> <val>\t", SetenvCmd}
cmds["Look"] = Cmd{"Editing", "[<text>]\tSearch <text> or starts interactive search", LookCmd}
cmds["New"] = Cmd{"Frames and Columns", "", NewCmd}
cmds["Newcol"] = Cmd{"Frames and Columns", "", NewcolCmd}
cmds["Paste"] = Cmd{"Clipboard", "[primary|indent]\t", PasteCmd}
cmds["Put"] = Cmd{"Files", "", PutCmd}
cmds["Putall"] = Cmd{"Files", "", PutallCmd}
cmds["Redo"] = Cmd{"Editing", "", RedoCmd}
cmds["Send"] = Cmd{"Misc", "", SendCmd}
cmds["Snarf"] = Cmd{"Clipboard", "Same as Copy", func(ec ExecContext, arg string) { CopyCmd(ec, arg, false) }}
cmds["Copy"] = Cmd{"Clipboard", "Copies current selection, or between mark and cursor if the selection is empty", func(ec ExecContext, arg string) { CopyCmd(ec, arg, false) }}
cmds["Sort"] = Cmd{"Frames and Columns", "Duplicates current frame", SortCmd}
cmds["Undo"] = Cmd{"Editing", "", UndoCmd}
cmds["Zerox"] = Cmd{"Frames and Columns", "Duplicates current frame", ZeroxCmd}
cmds["|"] = Cmd{"Jobs", "<ext. cmd.>\tRuns selection through <ext. cmd.> replaces with output", PipeCmd}
cmds["<"] = Cmd{"Jobs", "<ext. cmd.>\tRuns selection through <ext. cmd.>", PipeInCmd}
cmds[">"] = Cmd{"Jobs", "<ext. cmd.>\tReplaces selection with output of <ext. cmd.>", PipeOutCmd}
// New
cmds["Cd"] = Cmd{"Jobs", "<dir>\t", CdCmd}
cmds["Jobs"] = Cmd{"Jobs", "Lists currently running jobs", JobsCmd}
cmds["Look!Again"] = Cmd{"", "", LookAgainCmd}
cmds["Look!Quit"] = Cmd{"", "", func(ec ExecContext, arg string) { SpecialSendCmd(ec, "!Quit") }}
cmds["Look!Prev"] = Cmd{"", "", func(ec ExecContext, arg string) { SpecialSendCmd(ec, "!Prev") }}
cmds["Jump"] = Cmd{"Misc", "Swap cursor and mark", JumpCmd}
cmds["Getall"] = Cmd{"Files", "", GetallCmd}
cmds["Rename"] = Cmd{"Frames and Columns", "<name>\t", RenameCmd}
cmds["Rehash"] = Cmd{"Misc", "Recalculates completions", RehashCmd}
cmds["Do"] = Cmd{"Misc", "<…>\tExecutes sequence of commands, one per line", DoCmd}
cmds["Load"] = Cmd{"Session", "[<name>]\tLoads session from <name> (omit for a list of sessions)", LoadCmd}
cmds["Builtin"] = Cmd{"Misc", "<…>\tRuns command as builtin (skip attached processes)", BuiltinCmd}
cmds["Debug"] = Cmd{"Misc", "<…>\tRun without arguments for informations", DebugCmd}
cmds["Help"] = Cmd{"", "", HelpCmd}
cmds["Theme"] = Cmd{"Misc", "<name>\t", ThemeCmd}
cmds["Direxec"] = Cmd{"Misc", "Executes the specified command on the currently selected directory entry", DirexecCmd}
cmds["Mark"] = Cmd{"Misc", "Sets the mark", MarkCmd}
cmds["Savepos"] = Cmd{"Clipboard", "Copies current position of the cursor to clipboard", SaveposCmd}
cmds["Tooltip"] = Cmd{"Misc", "<cmd>\tExecutes a command and shows the result in a tooltip, if the output starts with the BEL character the tooltip will behave as autocompletion", TooltipCmd}
cmds["NextError"] = Cmd{"Misc", "Tries to load the file specified in the next line of the last editor where a load operation was executed", NextErrorCmd}
cmds["Lsp"] = Cmd{"Misc", "Language server management", LspCmd}
cmds["Prepare"] = Cmd{"", "", PrepareCmd}
// Not actually commands
cmds["LookFile"] = Cmd{"Frames and Columns", "", nil}
cmds["E"] = Cmd{"External Utilities", "<file>\tEdits file", nil}
cmds["Watch"] = Cmd{"External Utilities", "<cmd>\tExecutes command every time a file changes in current directory", nil}
cmds["win"] = Cmd{"External Utilities", "<cmd>\tRuns cmd within pty", nil}
cmds["y9p"] = Cmd{"External Utilities", " Filesystem interface access", nil}
cmds["Font"] = Cmd{"External Utilities", "Toggles alternate font", nil}
cmds["Fs"] = Cmd{"External Utilities", "Removes redundant spaces in current file", nil}
cmds["Indent"] = Cmd{"External Utilities", "Controls automatic indent and tab key behaviour", nil}
cmds["Tab"] = Cmd{"External Utilities", "Controls tab character width", nil}
cmds["LookExact"] = Cmd{"External Utilities", "Toggles smart case", nil}
cmds["Mount"] = Cmd{"External Utilities", "Invokes p9fuse", nil}
cmds["a+, a-"] = Cmd{"External Utilities", "indents/removes indent from selection", nil}
cmds["g"] = Cmd{"External Utilities", "recursive grep", nil}
cmds["in"] = Cmd{"External Utilities", "<dir> <cmd>\texecute <cmd> in <dir>", nil}
}
func HelpCmd(ec ExecContext, arg string) {
switch arg {
case "Edit":
Warn(`
== Commands ==
<addr>a/<text>/
Insert after
<addr>c/<text>/
Replace
<addr>i/<text>/
Insert before
<addr>d
Delete addr
<addr>s[<num>]/<regexp>/<text>/[g]
Replace all instances of <regexp> with <text>. If <num> is specified replaces only <num>-th occourence of <regexp>
<addr>m<addr>
Move from one address to another
<addr>t<addr>
Swap contents of the two addresses
<addr>p
Print contents of address
<addr>=
Print current line/column
<addr>x/<regexp>/<command>
Executes command for every match of <regexp>
<addr>y/<regexp>/<command>
Executes command for every sequence of text delimited by <regexp>
<addr>g/<regexp>/<command>
Executes command if the address matches <regexp>
<addr>v/<regexp>/<command>
Opposite of g
<addr>"<"<command>
<addr>">"<command>
<addr>"|"<command>
Executes external commands
<addr>k
Saves address as current selection
== Addresses ==
The initial <addr> can always be omitted, if it is it will default to "."
Simple Addresses:
#n empty string after n-th character
n n-th line
0 the point before the first character of the file
$ the point after the last character
#wn empty string after the n-th word
#?n don't use this
. whatever is currently selected
/regexp/
?regexp? forward or backward lookup for regexp match
/@regexp/
?@regexp? just like /regexp/ and ?regexp? but suppresses errors
Compound Addresses
a1+a2 address a2 evaluated starting at the end of a1
a1-a2 address a2 evaluated looking in the reverse direction starting at the beginning of a1
a1,a2 substring starting at the start of a1 and ending at the end of a2
a1;a2 like a1,a2 but with a2 evaluated after a1
For + and - if a2 is missing it defaults to "1", if a1 is missing it defaults to ".".
For , and ; if a2 is missing it defaults to "$", if a1 is missing it defaults to "0".
The address "," represents the whole file.
`)
case "Keybindings":
keys := []string{}
for k := range KeyBindings {
keys = append(keys, k)
}
sort.Strings(keys)
out := new(bytes.Buffer)
w := new(tabwriter.Writer)
w.Init(out, 0, 8, 0, '\t', 0)
for _, key := range keys {
fmt.Fprintf(w, "%s\t%s\n", key, KeyBindings[key].Str)
}
w.Flush()
Warn(out.String())
default:
out := new(bytes.Buffer)
fmt.Fprintf(out, `== Mouse ==
Select = left click (and drag)
Execute = middle click, control + left click
Search = right click, alt + left click
Execute with argument = control + middle click, control + right click, super + left click
Chords:
- Left + middle: cut
- Left + right: paste
- With left down, click middle and immediately after right: copy
`)
cat2cmds := map[string][]string{}
for name, cmd := range cmds {
cat2cmds[cmd.Category] = append(cat2cmds[cmd.Category], name)
}
describe := func(names []string) {
sort.Strings(names)
first := true
w := new(tabwriter.Writer)
w.Init(out, 0, 8, 0, '\t', 0)
for _, name := range names {
cmd := cmds[name]
if first {
fmt.Fprintf(out, "\n== %s ==\n", cmd.Category)
first = false
}
if cmd.Doc == "" {
fmt.Fprintf(w, "%s\t\n", name)
} else {
v := strings.Split(cmd.Doc, "\t")
if len(v) == 1 {
fmt.Fprintf(w, "%s\t%s\n", name, cmd.Doc)
} else {
fmt.Fprintf(w, "%s %s\t%s\n", name, v[0], v[1])
}
}
}
w.Flush()
}
for _, cat := range []string{"Files", "Editing", "Frames and Columns", "Clipboard", "Session", "Jobs", "External Utilities", "Misc"} {
describe(cat2cmds[cat])
delete(cat2cmds, cat)
}
cats := []string{}
for k := range cat2cmds {
cats = append(cats, k)
}
sort.Strings(cats)
for _, cat := range cats {
if cat == "" {
continue
}
describe(cat2cmds[cat])
}
fmt.Fprintf(out, `
Additional help:
Help Edit Help for the edit command
Help Keybindings Print current keybindings
`)
Warn(out.String())
}
}
func fakebuf(name string) bool {
return (len(name) == 0) || (name[0] == '+') || (name[0] == '-') || (name[len(name)-1] == '/')
}
func IntlCmd(cmd string) (CmdFn, string, string, bool) {
if len(cmd) <= 0 {
return nil, "", "", true
}
if (cmd[0] == '<') || (cmd[0] == '>') || (cmd[0] == '|') {
return cmds[cmd[:1]].Cmd, cmd[1:], cmd[:1], true
} else {
v := spacesRe.Split(cmd, 2)
if f, ok := macros[v[0]]; ok {
arg := ""
if len(v) > 1 {
arg = v[1]
}
return f, arg, v[0], true
} else if f, ok := cmds[v[0]]; ok && f.Cmd != nil {
arg := ""
if len(v) > 1 {
arg = v[1]
}
return f.Cmd, arg, v[0], true
} else {
return nil, "", "", false
}
}
}
func execGuard() {
if r := recover(); r != nil {
errmsg := fmt.Sprintf("%v\n", r)
if config.EditErrorTrace || strings.Contains(errmsg, "nil pointer") {
for i := 1; ; i++ {
_, file, line, ok := runtime.Caller(i)
if !ok {
break
}
errmsg += fmt.Sprintf(" %s:%d\n", file, line)
}
}
Warn(errmsg)
}
}
func Exec(ec ExecContext, cmd string) {
defer execGuard()
execNoDefer(ec, cmd)
}
func execNoDefer(ec ExecContext, cmd string) {
cmd = strings.TrimSpace(cmd)
xcmd, arg, _, isintl := IntlCmd(cmd)
if isintl {
if xcmd != nil {
xcmd(ec, arg)
}
} else {
ExtExec(ec, cmd, true)
}
}
func ExtExec(ec ExecContext, cmd string, dolog bool) {
wd := Wnd.tagbuf.Dir
if ec.dir != "" {
wd = ec.dir
}
if dolog {
LogExec(cmd, wd)
}
NewJob(wd, cmd, "", &ec, false, false, nil)
}
func BuiltinCmd(ec ExecContext, arg string) {
execNoDefer(ec, arg)
}
func col2active(ec *ExecContext) {
if activeSel.zeroxEd == nil {
return
}
ec.ed = activeSel.zeroxEd
ec.br = activeSel.zeroxEd.BufferRefresh
ec.fr = &ec.ed.sfr.Fr
ec.buf = ec.ed.bodybuf
ec.dir = ec.ed.bodybuf.Dir
}
func CopyCmd(ec ExecContext, arg string, del bool) {
exitConfirmed = false
if ec.ed != nil {
ec.ed.confirmDel = false
ec.ed.confirmSave = false
}
if (ec.buf == nil) || (ec.fr == nil) || (ec.br == nil) {
return
}
if ec.ed != nil && ec.buf == ec.ed.bodybuf && ec.fr.Sel.S == ec.fr.Sel.E && ec.ed.otherSel[OS_MARK].S >= 0 && ec.ed.otherSel[OS_MARK].E >= 0 {
if ec.ed.otherSel[OS_MARK].S >= ec.fr.Sel.S {
ec.fr.Sel.E = ec.ed.otherSel[OS_MARK].S
} else {
ec.fr.Sel.S = ec.ed.otherSel[OS_MARK].S
}
ec.ed.otherSel[OS_MARK] = util.Sel{-1, -1}
}
s := string(ec.buf.SelectionRunes(ec.fr.Sel))
if s == "" {
// Does not trash clipboard when accidentally copying nil text
return
}
if del {
ec.buf.Replace([]rune{}, &ec.fr.Sel, true, ec.eventChan, util.EO_MOUSE)
if !ec.norefresh {
ec.br()
}
}
clipboard.Set(s)
}
func DelCmd(ec ExecContext, arg string, confirmed bool) {
exitConfirmed = false
clearToRemove := !ec.ed.bodybuf.Modified || fakebuf(ec.ed.bodybuf.Name) || confirmed || ec.ed.confirmDel
if !clearToRemove {
count := 0
for i := range Wnd.cols.cols {
for j := range Wnd.cols.cols[i].editors {
if ec.ed.bodybuf == Wnd.cols.cols[i].editors[j].bodybuf {
count++
}
}
}
clearToRemove = count > 1
}
if clearToRemove {
if ec.ed.eventChan != nil {
close(ec.ed.eventChan)
ec.ed.eventChan = nil
}
Log(ec.ed.edid, LOP_DEL, ec.ed.bodybuf)
col := ec.ed.Column()
col.Remove(col.IndexOf(ec.ed))
ec.ed.Close()
removeBuffer(ec.ed.bodybuf)
Wnd.FlushImage(col.r)
} else {
ec.ed.confirmDel = true
Warn("File " + ec.ed.bodybuf.ShortName() + " has unsaved changes")
}
}
func DelcolCmd(ec ExecContext, arg string) {
exitConfirmed = false
if ec.col == nil {
return
}
if len(Wnd.cols.cols) <= 1 {
return
}
t := "The following files have unsaved changes:\n"
n := 0
for _, ed := range ec.col.editors {
if ed.bodybuf.Modified && !fakebuf(ed.bodybuf.Name) && !ed.confirmDel {
ed.confirmDel = true
t += ed.bodybuf.ShortName() + "\n"
n++
}
}
if n > 0 {
if time.Since(ec.col.closeRequested) > (3*time.Second) && len(ec.col.editors) > 0 {
Warn(t)
ec.col.closeRequested = time.Now()
return
}
}
for _, ed := range ec.col.editors {
removeBuffer(ed.bodybuf)
}
Wnd.cols.Remove(Wnd.cols.IndexOf(ec.col))
ec.col.Close()
Wnd.FlushImage()
}
func DumpCmd(ec ExecContext, arg string) {
exitConfirmed = false
dumpDest := getDumpPath(arg, true)
if DumpTo(dumpDest) {
AutoDumpPath = dumpDest
setDumpTitle()
}
}
type fileInfoSortByTime []os.FileInfo
func (f fileInfoSortByTime) Len() int {
return len(f)
}
func (f fileInfoSortByTime) Less(i, j int) bool {
return f[i].ModTime().Unix() >= f[j].ModTime().Unix()
}
func (f fileInfoSortByTime) Swap(i, j int) {
t := f[i]
f[i] = f[j]
f[j] = t
}
func LoadCmd(ec ExecContext, arg string) {
exitConfirmed = false
if strings.TrimSpace(arg) == "" {
wd, _ := os.Getwd()
dh, err := os.Open(os.ExpandEnv("$HOME/.config/yacco/"))
if err == nil {
defer dh.Close()
var fis fileInfoSortByTime
fis, err := dh.Readdir(-1)
if err != nil {
fis = []os.FileInfo{}
}
sort.Sort(fis)
r := []string{}
for i := range fis {
n := fis[i].Name()
if !strings.HasSuffix(n, ".dump") {
continue
}
r = append(r, fmt.Sprintf("Load %s", n[:len(n)-len(".dump")]))
}
Warnfull("+Dumps", strings.Join(r, "\n"), false, false)
Warnfull("+Dumps", "\n", false, false)
ded, _ := EditFind(wd, "+Dumps", false, false)
if ded != nil {
ded.sfr.Fr.Sel = util.Sel{0, 0}
ded.BufferRefresh()
}
}
} else {
dumpDest := getDumpPath(arg, false)
if LoadFrom(dumpDest) {
AutoDumpPath = dumpDest
setDumpTitle()
}
}
}
func getDumpPath(arg string, dodef bool) string {
dumpDest := strings.TrimSpace(arg)
if dumpDest == "" {
if AutoDumpPath != "" {
return AutoDumpPath
}
if !dodef {
return ""
}
dumpDest = "default"
}
dumpDest = filepath.Join(os.Getenv("HOME"), ".config", "yacco", dumpDest+".dump")
return dumpDest
}
func EditCmd(ec ExecContext, arg string) {
editCmd(ec, arg, false)
}
func editCmd(ec ExecContext, arg string, trace bool) {
exitConfirmed = false
if ec.ed != nil {
ec.ed.confirmDel = false
ec.ed.confirmSave = false
}
if (ec.buf == nil) || (ec.fr == nil) || (ec.br == nil) {
edit.Edit(arg, makeEditContext(nil, nil, nil, nil, trace))
} else {
edit.Edit(arg, makeEditContext(ec.buf, &ec.fr.Sel, ec.eventChan, ec.ed, trace))
if !ec.norefresh {
ec.br()
}
}
}
func ExitCmd(ec ExecContext, arg string) {
t := "The following files have unsaved changes:\n"
n := 0
for i := range Wnd.cols.cols {
for j := range Wnd.cols.cols[i].editors {
buf := Wnd.cols.cols[i].editors[j].bodybuf
if buf.Modified && !fakebuf(buf.Name) {
t += buf.ShortName() + "\n"
n++
}
}
}
if (n == 0) || exitConfirmed {
FsQuit()
} else {
exitConfirmed = true
Warn(t)
}
}
func JobsCmd(ec ExecContext, arg string) {
UpdateJobs(true)
}
func KillCmd(ec ExecContext, arg string) {
exitConfirmed = false
arg = strings.TrimSpace(arg)
if arg == "" {
jobKillLast()
} else {
if n, err := strconv.Atoi(arg); err == nil {
jobKill(n)
} else {
if n := FindJobByName(arg); n >= 0 {
jobKill(n)
}
}
}
}
func SetenvCmd(ec ExecContext, arg string) {
exitConfirmed = false
v := spacesRe.Split(arg, 2)
switch len(v) {
case 1:
os.Unsetenv(v[0])
case 2:
os.Setenv(v[0], v[1])
default:
Warn("Setenv: wrong number of arguments")
}
}
func LookCmd(ec ExecContext, arg string) {
exitConfirmed = false
if ec.ed == nil {
return
}
ec.ed.confirmDel = false
ec.ed.confirmSave = false
if arg != "" {
lookfwd(ec.ed, []rune(arg), true, Wnd.Prop["lookexact"] == "yes")
} else {
ec.fr = &ec.ed.sfr.Fr
go lookproc(ec)
}
}
func LookAgainCmd(ec ExecContext, arg string) {
exitConfirmed = false
if ec.ed == nil {
return
}
if ec.ed.eventChanSpecial && ec.ed.eventChan != nil {
SpecialSendCmd(ec, "Look!Again")
} else {
lookfwd(ec.ed, lastNeedle, true, Wnd.Prop["lookexact"] == "yes")
}
}
func SpecialSendCmd(ec ExecContext, msg string) {
exitConfirmed = false
if (ec.ed == nil) || !ec.ed.eventChanSpecial || (ec.ed.eventChan == nil) {
return
}
ec.ed.confirmDel = false
ec.ed.confirmSave = false
util.Fmtevent2(ec.ed.eventChan, util.EO_KBD, true, false, false, 0, 0, 0, msg, nil)
}
func GetCmd(ec ExecContext, arg string) {
getCmdIntl(ec, arg, false)
}
func getCmdIntl(ec ExecContext, arg string, special bool) {
exitConfirmed = false
if ec.ed == nil {
return
}
if ec.ed.bodybuf.Modified && !ec.ed.confirmDel && !ec.ed.bodybuf.IsDir() {
ec.ed.confirmDel = true
Warn("File " + ec.ed.bodybuf.ShortName() + " has unsaved changes")
return
}
Log(ec.ed.edid, LOP_GET, ec.ed.bodybuf)
if ec.ed.bodybuf.IsDir() {
ec.ed.readDir()
} else {
flag := buf.ReloadCreate
if special {
flag |= buf.ReloadPreserveCurlineWhitespace
}
ec.ed.bodybuf.Reload(flag)
ec.ed.FixTop()
}
if !ec.norefresh {
ec.ed.TagRefresh()
ec.ed.BufferRefresh()
}
}
func NewCmd(ec ExecContext, arg string) {
exitConfirmed = false
arg = strings.TrimSpace(arg)
if arg == "" {
arg = "+New"
}
path := util.ResolvePath(ec.dir, arg)
ed, err := HeuristicOpen(path, true, true)
if err != nil {
Warn("New: " + err.Error())
} else {
if ed != nil && AutoDumpPath == "" && FirstOpenFile {
historyAdd(filepath.Join(ed.bodybuf.Dir, ed.bodybuf.Name))
}
}
}
func NewcolCmd(ec ExecContext, arg string) {
exitConfirmed = false
Wnd.cols.AddAfter(NewCol(&Wnd, Wnd.cols.r), -1, 0.4)
Wnd.FlushImage()
}
func PasteCmd(ec ExecContext, arg string) {
exitConfirmed = false
if ec.ed != nil {
ec.ed.confirmDel = false
ec.ed.confirmSave = false
}
if (ec.buf == nil) || (ec.fr == nil) || (ec.br == nil) {
return
}
var cb string
switch arg {
case "Indent", "indent":
PasteIndentCmd(ec, arg)
return
case "Primary", "primary":
cb = clipboard.GetPrimary()
default:
cb = clipboard.Get()
}
ec.buf.Replace([]rune(cb), &ec.fr.Sel, true, ec.eventChan, util.EO_MOUSE)
if !ec.norefresh {
ec.br()
}
}
func PasteIndentCmd(ec ExecContext, arg string) {
exitConfirmed = false
if ec.ed != nil {
ec.ed.confirmDel = false
ec.ed.confirmSave = false
}
if (ec.buf == nil) || (ec.fr == nil) || (ec.br == nil) {
return
}
cb := clipboard.Get()
if (ec.fr.Sel.S == 0) || (ec.fr.Sel.S != ec.fr.Sel.E) || (ec.ed == nil) || (ec.buf != ec.ed.bodybuf) {
ec.buf.Replace([]rune(cb), &ec.fr.Sel, true, ec.eventChan, util.EO_MOUSE)
if !ec.norefresh {
ec.br()
}
return
}
failed := false
tgtIndent := ""
tgtIndentSearch:
for i := ec.fr.Sel.S - 1; i > 0; i-- {
r := ec.buf.At(i)
switch r {
case '\n':
tgtIndent = string(ec.buf.SelectionRunes(util.Sel{i + 1, ec.fr.Sel.S}))
break tgtIndentSearch
case ' ', '\t':
// continue
default:
failed = true
break tgtIndentSearch
}
}
if failed {
ec.buf.Replace([]rune(cb), &ec.fr.Sel, true, ec.eventChan, util.EO_MOUSE)
if !ec.norefresh {
ec.br()
}
return
}
pasteLines := strings.Split(cb, "\n")
srcIndent := ""
for i := range pasteLines[0] {
if (pasteLines[0][i] != ' ') && (pasteLines[0][i] != '\t') {
srcIndent = pasteLines[0][:i]
break
}
}
for i := range pasteLines {
if strings.HasPrefix(pasteLines[i], srcIndent) {
if i == 0 {
pasteLines[i] = pasteLines[i][len(srcIndent):]
} else {
pasteLines[i] = tgtIndent + pasteLines[i][len(srcIndent):]
}
} else if (i == len(pasteLines)-1) && (pasteLines[i] == "") {
pasteLines[i] = tgtIndent
} else {
pasteLines[i] = pasteLines[i]
}
}
ecb := strings.Join(pasteLines, "\n")
ec.buf.Replace([]rune(ecb), &ec.fr.Sel, true, ec.eventChan, util.EO_MOUSE)
if !ec.norefresh {
ec.br()
}
}
func PutCmd(ec ExecContext, arg string) {
exitConfirmed = false
if ec.ed == nil {
return
}
ec.ed.confirmDel = false
if fakebuf(ec.ed.bodybuf.Name) {
return
}
triggeredSaveRules := make(map[string][]string)
if !ec.ed.confirmSave {
if !ec.ed.bodybuf.CanSave() {
ec.ed.confirmSave = true
Warn(fmt.Sprintf("Put: %s changed on disk, are you sure you want to overwrite?\nDiskDiff %d", ec.ed.bodybuf.ShortName(), ec.ed.edid))
return
}
}
Log(ec.ed.edid, LOP_PUT, ec.ed.bodybuf)
err := ec.ed.bodybuf.Put()
if err != nil {
Warn(fmt.Sprintf("Put: Couldn't save %s: %s", ec.ed.bodybuf.ShortName(), err.Error()))
} else {
registerSaveRule(ec.ed.bodybuf.Path(), triggeredSaveRules)
}
if !ec.norefresh {
ec.ed.BufferRefresh()
}
if AutoDumpPath != "" {
DumpTo(AutoDumpPath)
}
if config.IsTemplatesFile(filepath.Join(ec.ed.bodybuf.Dir, ec.ed.bodybuf.Name)) {
config.LoadTemplates()
}
runSaveRules(triggeredSaveRules)
}
func PutallCmd(ec ExecContext, arg string) {
exitConfirmed = false
t := "Putall: Saving the following files failed:\n"
nerr := 0
triggeredSaveRules := make(map[string][]string)
for _, col := range Wnd.cols.cols {
for _, ed := range col.editors {
if !fakebuf(ed.bodybuf.Name) && ed.bodybuf.Modified {
err := ed.bodybuf.Put()
if err != nil {
t += ed.bodybuf.ShortName() + ": " + err.Error() + "\n"
nerr++
} else {
registerSaveRule(ed.bodybuf.Path(), triggeredSaveRules)
}
if !ec.norefresh {
ed.BufferRefresh()
}
if config.IsTemplatesFile(ed.bodybuf.Path()) {
config.LoadTemplates()
}
}
}
}
if nerr != 0 {
Warn(t)
}
if AutoDumpPath != "" {
DumpTo(AutoDumpPath)
}
runSaveRules(triggeredSaveRules)
}
func registerSaveRule(path string, triggeredSaveRules map[string][]string) {
if sr := config.SaveRuleFor(path); sr != nil {
triggeredSaveRules[sr.Cmd] = append(triggeredSaveRules[sr.Cmd], path)
}
}
func runSaveRules(triggeredSaveRules map[string][]string) {
for srcmd, files := range triggeredSaveRules {
NewJob(Wnd.tagbuf.Dir, fmt.Sprintf("%s %s", srcmd, strings.Join(files, " ")), "", &ExecContext{}, false, false, nil)
}
}
func GetallCmd(ec ExecContext, arg string) {
exitConfirmed = false
t := "Getall: Not reloading the following modified buffers:\n"
nerr := 0
for _, col := range Wnd.cols.cols {
for _, ed := range col.editors {
if !fakebuf(ed.bodybuf.Name) {
if ed.bodybuf.Modified {
t += ed.bodybuf.ShortName() + "\n"
nerr++
} else {
ed.bodybuf.Reload(buf.ReloadCreate)
ed.FixTop()
ed.BufferRefresh()
}
}
}
}
if nerr != 0 {
Warn(t)
}
lsp.Killall() // if there is a LSP server kill it
}
func RedoCmd(ec ExecContext, arg string) {
exitConfirmed = false
if ec.ed == nil {
return
}
ec.ed.confirmDel = false
ec.ed.confirmSave = false
ec.buf.Undo(&ec.fr.Sel, true)
if !ec.norefresh {
ec.br()
}
}
func SendCmd(ec ExecContext, arg string) {
exitConfirmed = false
if ec.ed == nil {
return
}
ec.ed.confirmDel = false
ec.ed.confirmSave = false
txt := []rune{}
if ec.ed.sfr.Fr.Sel.S != ec.ed.sfr.Fr.Sel.E {
txt = ec.ed.bodybuf.SelectionRunes(ec.ed.sfr.Fr.Sel)
} else {
txt = []rune(clipboard.Get())
}
ec.ed.sfr.Fr.SelColor = 0
ec.ed.sfr.Fr.Sel = util.Sel{ec.buf.Size(), ec.buf.Size()}
if (len(txt) > 0) && (txt[len(txt)-1] != '\n') {
txt = append(txt, rune('\n'))
}
ec.ed.bodybuf.Replace(txt, &ec.ed.sfr.Fr.Sel, true, ec.eventChan, util.EO_MOUSE)
if !ec.norefresh {
ec.ed.BufferRefresh()
}
}
func SortCmd(ec ExecContext, arg string) {
exitConfirmed = false
if ec.col == nil {
return
}
sort.Sort((*Editors)(&ec.col.editors))
ec.col.RecalcRects(ec.col.last)
ec.col.Redraw()
Wnd.FlushImage(ec.col.r)
}
func UndoCmd(ec ExecContext, arg string) {
exitConfirmed = false
if (ec.ed == nil) || (ec.buf == nil) {
return
}
ec.ed.confirmDel = false
ec.ed.confirmSave = false
ec.buf.Undo(&ec.fr.Sel, false)
if ec.br != nil && !ec.norefresh {
ec.br()
}
}
func ZeroxCmd(ec ExecContext, arg string) {
exitConfirmed = false
ed := ec.ed
if ed == nil {