-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
1429 lines (1374 loc) · 40.3 KB
/
Copy pathmain.go
File metadata and controls
1429 lines (1374 loc) · 40.3 KB
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 (
"fmt"
"os"
"strconv"
"strings"
"github.com/mattn/go-runewidth"
"github.com/ryogrid/goomacs/term"
)
const tabWidth = 8
// modeHandlers maps buffer mode names to key event handlers.
// If a handler returns true, the key is consumed and normal processing is skipped.
var modeHandlers = map[string]func(ev *term.KeyEvent, buf *Buffer, message *string) bool{}
// splitMode tracks the current window split orientation.
// It is "vertical" (top/bottom, C-x 2) or "horizontal" (side-by-side, C-x 3).
var splitMode = "vertical"
// Editor state — package-level so commands in other files can access them.
var buffers []*Buffer
var activeBufferIdx int
var previousBufferIdx int
// Minibuffer state — package-level so commands in other files can set them.
var minibufferMode bool // true when minibuffer input is active
var minibufferPrompt string // prompt shown before input
var minibufferInput []rune // current input text
var minibufferCursorPos int // cursor position within minibufferInput
var minibufferCallback func(string) // called with input on Enter
// refreshBufferList updates the content of the *Buffer List* buffer if it exists.
// This should be called after any operation that changes the buffers slice.
func refreshBufferList() {
var blBuf *Buffer
for _, b := range buffers {
if b.Filename == "*Buffer List*" {
blBuf = b
break
}
}
if blBuf == nil {
return
}
var lines []string
for i, b := range buffers {
marker := " "
if i == activeBufferIdx {
marker = ">"
}
modFlag := " "
if b.Modified {
modFlag = "*"
}
name := b.Filename
if name == "" {
name = "[No Name]"
}
lines = append(lines, fmt.Sprintf("%s%s %s", marker, modFlag, name))
}
content := strings.Join(lines, "\n")
rawLines := strings.Split(content, "\n")
blBuf.Lines = make([][]rune, len(rawLines))
for i, rl := range rawLines {
blBuf.Lines[i] = []rune(rl)
}
if blBuf.CursorR >= len(blBuf.Lines) {
blBuf.CursorR = len(blBuf.Lines) - 1
}
blBuf.Modified = false
}
// bufColToVisualCol converts a buffer column index to a visual (screen) column
// for the given line, accounting for tab expansion.
func bufColToVisualCol(line []rune, bufCol int) int {
visualCol := 0
for i := 0; i < bufCol && i < len(line); i++ {
if line[i] == '\t' {
visualCol += tabWidth - (visualCol % tabWidth)
} else {
visualCol += runewidth.RuneWidth(line[i])
}
}
return visualCol
}
// Window represents a view into a buffer on screen.
type Window struct {
Buffer *Buffer
ScrollOffset int
StartRow int // first screen row
Height int // total rows including status line
StartCol int // first screen column (used in horizontal split)
Width int // columns allocated to this window
}
// ViewHeight returns the number of rows available for text (excluding the status line).
func (w *Window) ViewHeight() int {
h := w.Height - 1
if h < 1 {
h = 1
}
return h
}
// AdjustScroll ensures the cursor is visible within this window's viewport.
func (w *Window) AdjustScroll() {
viewH := w.ViewHeight()
if w.Buffer.CursorR < w.ScrollOffset {
w.ScrollOffset = w.Buffer.CursorR
}
if w.Buffer.CursorR >= w.ScrollOffset+viewH {
w.ScrollOffset = w.Buffer.CursorR - viewH + 1
}
}
// ScrollDown scrolls the window down by one page.
func (w *Window) ScrollDown() {
viewH := w.ViewHeight()
w.ScrollOffset += viewH
maxOffset := len(w.Buffer.Lines) - 1
if w.ScrollOffset > maxOffset {
w.ScrollOffset = maxOffset
}
if w.Buffer.CursorR < w.ScrollOffset {
w.Buffer.CursorR = w.ScrollOffset
if w.Buffer.CursorC > len(w.Buffer.Lines[w.Buffer.CursorR]) {
w.Buffer.CursorC = len(w.Buffer.Lines[w.Buffer.CursorR])
}
}
}
// ScrollUp scrolls the window up by one page.
func (w *Window) ScrollUp() {
viewH := w.ViewHeight()
w.ScrollOffset -= viewH
if w.ScrollOffset < 0 {
w.ScrollOffset = 0
}
lastVisible := w.ScrollOffset + viewH - 1
if lastVisible >= len(w.Buffer.Lines) {
lastVisible = len(w.Buffer.Lines) - 1
}
if w.Buffer.CursorR > lastVisible {
w.Buffer.CursorR = lastVisible
if w.Buffer.CursorC > len(w.Buffer.Lines[w.Buffer.CursorR]) {
w.Buffer.CursorC = len(w.Buffer.Lines[w.Buffer.CursorR])
}
}
}
// recalcWindows distributes available screen space evenly among windows.
// The last row is reserved for the message line.
// In vertical mode, windows stack top-to-bottom with full width.
// In horizontal mode, windows are placed side-by-side (handled in later stories).
func recalcWindows(windows []*Window, screenWidth, screenHeight int) {
n := len(windows)
if splitMode == "horizontal" && n > 1 {
// Horizontal (side-by-side) layout: distribute width evenly.
// Reserve 1 column between each pair of adjacent windows for separators.
available := screenWidth - (n - 1)
if available < n {
available = n
}
baseW := available / n
extra := available % n
col := 0
for i, w := range windows {
w.StartCol = col
w.Width = baseW
if i < extra {
w.Width++
}
w.StartRow = 0
w.Height = screenHeight - 1 // full height minus message line
col += w.Width + 1 // +1 for separator column
}
} else {
// Vertical (top/bottom) layout: distribute height evenly.
available := screenHeight - 1 // reserve 1 row for message line
if available < n {
available = n
}
baseH := available / n
extra := available % n
row := 0
for i, w := range windows {
w.StartRow = row
w.Height = baseH
if i < extra {
w.Height++
}
w.StartCol = 0
w.Width = screenWidth
row += w.Height
}
}
}
func main() {
// Load buffers from file arguments or create empty *scratch* buffer.
if len(os.Args) > 1 {
for _, filename := range os.Args[1:] {
b, err := NewBufferFromFile(filename)
if err != nil {
if os.IsNotExist(err) {
b = NewBuffer()
b.Filename = filename
b.Highlight = NewHighlighter(filename)
} else {
fmt.Fprintf(os.Stderr, "error opening file: %v\n", err)
os.Exit(1)
}
}
buffers = append(buffers, b)
}
} else {
scratch := NewBuffer()
scratch.Filename = "*scratch*"
buffers = append(buffers, scratch)
}
activeBufferIdx = 0
previousBufferIdx = 0
buf := buffers[activeBufferIdx]
// Create initial window showing the active buffer.
windows := []*Window{{Buffer: buf, ScrollOffset: 0}}
activeWindowIdx := 0
screen := term.NewTerminal()
editorScreen = screen
if err := screen.Init(); err != nil {
fmt.Fprintf(os.Stderr, "error initializing screen: %v\n", err)
os.Exit(1)
}
defer screen.Fini()
screenWidth, screenHeight := screen.Size()
recalcWindows(windows, screenWidth, screenHeight)
var message string // message to display in message area
var prefixCx bool // true when C-x prefix has been pressed
var quitWarned bool // true after warning about unsaved changes on C-x C-c
var searchMode bool // true when in incremental search
var searchForward bool // true for forward search, false for backward
var searchQuery []rune // current search query
var searchOrigR int // cursor row before search started
var searchOrigC int // cursor col before search started
var searchMatchR int // row of current match (for highlight)
var searchMatchC int // col of current match (for highlight)
var searchHasMatch bool // true if current query has a match
var confirmMode bool // true when waiting for y/n confirmation
var confirmCallback func(bool) // called with true for y, false for n
redraw := func() {
screen.Clear()
activeWin := windows[activeWindowIdx]
for i, win := range windows {
if i == activeWindowIdx {
win.AdjustScroll()
}
isActive := i == activeWindowIdx
if isActive && searchMode && searchHasMatch {
drawWindowContent(screen, win, searchHighlight{
active: true,
matchR: searchMatchR,
matchC: searchMatchC,
queryLen: len(searchQuery),
})
} else {
drawWindowContent(screen, win, searchHighlight{})
}
drawWindowStatusLine(screen, win, isActive)
}
// Draw vertical separators between horizontal windows.
if splitMode == "horizontal" && len(windows) > 1 {
for i := 0; i < len(windows)-1; i++ {
sepCol := windows[i].StartCol + windows[i].Width
for row := 0; row < screenHeight-1; row++ {
screen.SetContent(sepCol, row, '│', term.StyleDefault)
}
}
}
drawMessageLine(screen, message)
if minibufferMode {
cursorX := len([]rune(minibufferPrompt)) + minibufferCursorPos
screen.ShowCursor(cursorX, screenHeight-1)
} else {
screen.ShowCursor(
activeWin.StartCol+bufColToVisualCol(activeWin.Buffer.Lines[activeWin.Buffer.CursorR], activeWin.Buffer.CursorC),
activeWin.Buffer.CursorR-activeWin.ScrollOffset+activeWin.StartRow,
)
}
screen.Show()
}
redraw()
for {
ev := screen.PollEvent()
switch ev := ev.(type) {
case *term.KeyEvent:
screenWidth, screenHeight = screen.Size()
recalcWindows(windows, screenWidth, screenHeight)
message = "" // clear message on next key
activeWin := windows[activeWindowIdx]
// Handle search mode
if searchMode {
switch ev.Key() {
case term.KeyCtrlS:
// Search forward for next match
searchForward = true
if len(searchQuery) > 0 {
startR, startC := buf.CursorR, buf.CursorC+1
if startC > len(buf.Lines[startR]) {
startR++
startC = 0
if startR >= len(buf.Lines) {
startR = 0
}
}
r, c, ok := buf.SearchForward(searchQuery, startR, startC)
if ok {
buf.CursorR, buf.CursorC = r, c
searchMatchR, searchMatchC = r, c
searchHasMatch = true
message = fmt.Sprintf("I-search: %s", string(searchQuery))
} else {
message = fmt.Sprintf("Failing I-search: %s", string(searchQuery))
searchHasMatch = false
}
}
case term.KeyCtrlR:
// Search backward for previous match
searchForward = false
if len(searchQuery) > 0 {
startR, startC := buf.CursorR, buf.CursorC
r, c, ok := buf.SearchBackward(searchQuery, startR, startC)
if ok {
buf.CursorR, buf.CursorC = r, c
searchMatchR, searchMatchC = r, c
searchHasMatch = true
message = fmt.Sprintf("I-search backward: %s", string(searchQuery))
} else {
message = fmt.Sprintf("Failing I-search backward: %s", string(searchQuery))
searchHasMatch = false
}
}
case term.KeyCtrlG:
// Cancel search, restore original position
buf.CursorR = searchOrigR
buf.CursorC = searchOrigC
searchMode = false
searchHasMatch = false
message = "Quit"
case term.KeyEnter, term.KeyCtrlJ:
// Accept search result, exit search mode
searchMode = false
searchHasMatch = false
message = ""
case term.KeyBackspace, term.KeyBackspace2, term.KeyCtrlH:
// Delete last character from search query
if len(searchQuery) > 0 {
searchQuery = searchQuery[:len(searchQuery)-1]
if len(searchQuery) > 0 {
// Re-search from original position
var r, c int
var ok bool
if searchForward {
r, c, ok = buf.SearchForward(searchQuery, searchOrigR, searchOrigC)
} else {
r, c, ok = buf.SearchBackward(searchQuery, searchOrigR, searchOrigC)
}
if ok {
buf.CursorR, buf.CursorC = r, c
searchMatchR, searchMatchC = r, c
searchHasMatch = true
} else {
searchHasMatch = false
}
if searchForward {
message = fmt.Sprintf("I-search: %s", string(searchQuery))
} else {
message = fmt.Sprintf("I-search backward: %s", string(searchQuery))
}
} else {
buf.CursorR = searchOrigR
buf.CursorC = searchOrigC
searchHasMatch = false
if searchForward {
message = "I-search: "
} else {
message = "I-search backward: "
}
}
}
case term.KeyRune:
// Add character to search query
searchQuery = append(searchQuery, ev.Rune())
var r, c int
var ok bool
if searchForward {
r, c, ok = buf.SearchForward(searchQuery, buf.CursorR, buf.CursorC)
} else {
r, c, ok = buf.SearchBackward(searchQuery, buf.CursorR, buf.CursorC+1)
}
if ok {
buf.CursorR, buf.CursorC = r, c
searchMatchR, searchMatchC = r, c
searchHasMatch = true
if searchForward {
message = fmt.Sprintf("I-search: %s", string(searchQuery))
} else {
message = fmt.Sprintf("I-search backward: %s", string(searchQuery))
}
} else {
if searchForward {
message = fmt.Sprintf("Failing I-search: %s", string(searchQuery))
} else {
message = fmt.Sprintf("Failing I-search backward: %s", string(searchQuery))
}
searchHasMatch = false
}
default:
// Any other key exits search mode and is NOT consumed
searchMode = false
searchHasMatch = false
message = ""
// Re-post the event so it gets handled normally
screen.PostEvent(ev)
redraw()
continue
}
redraw()
continue
}
// Handle minibuffer input mode
if minibufferMode {
switch ev.Key() {
case term.KeyEnter, term.KeyCtrlJ:
input := string(minibufferInput)
cb := minibufferCallback
minibufferMode = false
minibufferInput = nil
minibufferCursorPos = 0
minibufferCallback = nil
message = ""
if cb != nil {
cb(input)
}
case term.KeyCtrlG, term.KeyEsc:
minibufferMode = false
minibufferInput = nil
minibufferCursorPos = 0
minibufferCallback = nil
message = "Quit"
case term.KeyBackspace, term.KeyBackspace2, term.KeyCtrlH:
if minibufferCursorPos > 0 {
minibufferInput = append(minibufferInput[:minibufferCursorPos-1], minibufferInput[minibufferCursorPos:]...)
minibufferCursorPos--
}
message = minibufferPrompt + string(minibufferInput)
case term.KeyLeft, term.KeyCtrlB:
if minibufferCursorPos > 0 {
minibufferCursorPos--
}
message = minibufferPrompt + string(minibufferInput)
case term.KeyRight, term.KeyCtrlF:
if minibufferCursorPos < len(minibufferInput) {
minibufferCursorPos++
}
message = minibufferPrompt + string(minibufferInput)
case term.KeyCtrlA:
minibufferCursorPos = 0
message = minibufferPrompt + string(minibufferInput)
case term.KeyCtrlE:
minibufferCursorPos = len(minibufferInput)
message = minibufferPrompt + string(minibufferInput)
case term.KeyCtrlD:
if minibufferCursorPos < len(minibufferInput) {
minibufferInput = append(minibufferInput[:minibufferCursorPos], minibufferInput[minibufferCursorPos+1:]...)
}
message = minibufferPrompt + string(minibufferInput)
case term.KeyCtrlK:
if minibufferCursorPos < len(minibufferInput) {
minibufferInput = minibufferInput[:minibufferCursorPos]
}
message = minibufferPrompt + string(minibufferInput)
case term.KeyTab:
// Tab completion for Find file
if minibufferPrompt == "Find file: " {
input := string(minibufferInput)
dir := "."
prefix := input
if idx := strings.LastIndex(input, "/"); idx >= 0 {
dir = input[:idx]
if dir == "" {
dir = "/"
}
prefix = input[idx+1:]
}
entries, err := os.ReadDir(dir)
if err == nil {
var matches []string
for _, e := range entries {
name := e.Name()
if strings.HasPrefix(name, prefix) {
if e.IsDir() {
matches = append(matches, name+"/")
} else {
matches = append(matches, name)
}
}
}
if len(matches) == 1 {
if dir == "." {
minibufferInput = []rune(matches[0])
minibufferCursorPos = len(minibufferInput)
} else {
minibufferInput = []rune(dir + "/" + matches[0])
minibufferCursorPos = len(minibufferInput)
}
} else if len(matches) > 1 {
common := longestCommonPrefix(matches)
if dir == "." {
minibufferInput = []rune(common)
minibufferCursorPos = len(minibufferInput)
} else {
minibufferInput = []rune(dir + "/" + common)
minibufferCursorPos = len(minibufferInput)
}
message = minibufferPrompt + string(minibufferInput) + " [" + strings.Join(matches, " ") + "]"
redraw()
continue
}
}
message = minibufferPrompt + string(minibufferInput)
} else if minibufferPrompt == "M-x " {
input := string(minibufferInput)
matches := FindCommandsByPrefix(input)
if len(matches) == 1 {
minibufferInput = []rune(matches[0].Name)
minibufferCursorPos = len(minibufferInput)
} else if len(matches) > 1 {
var names []string
for _, m := range matches {
names = append(names, m.Name)
}
message = strings.Join(names, " ")
redraw()
continue
}
message = minibufferPrompt + string(minibufferInput)
} else if strings.HasPrefix(minibufferPrompt, "Kill buffer:") || minibufferPrompt == "Switch to buffer: " {
input := string(minibufferInput)
var names []string
for _, b := range buffers {
name := b.Filename
if name == "" {
name = "[No Name]"
}
if strings.HasPrefix(name, input) {
names = append(names, name)
}
}
if len(names) == 1 {
minibufferInput = []rune(names[0])
minibufferCursorPos = len(minibufferInput)
} else if len(names) > 1 {
common := longestCommonPrefix(names)
minibufferInput = []rune(common)
minibufferCursorPos = len(minibufferInput)
message = minibufferPrompt + string(minibufferInput) + " [" + strings.Join(names, " ") + "]"
redraw()
continue
}
message = minibufferPrompt + string(minibufferInput)
}
case term.KeyRune:
tail := make([]rune, len(minibufferInput[minibufferCursorPos:]))
copy(tail, minibufferInput[minibufferCursorPos:])
minibufferInput = append(append(minibufferInput[:minibufferCursorPos], ev.Rune()), tail...)
minibufferCursorPos++
message = minibufferPrompt + string(minibufferInput)
default:
// All other keys are ignored in minibuffer mode
message = minibufferPrompt + string(minibufferInput)
}
redraw()
continue
}
// Handle y/n confirmation mode
if confirmMode {
if ev.Key() == term.KeyRune {
switch ev.Rune() {
case 'y':
confirmMode = false
cb := confirmCallback
confirmCallback = nil
if cb != nil {
cb(true)
}
case 'n':
confirmMode = false
confirmCallback = nil
message = "Cancelled"
}
} else if ev.Key() == term.KeyCtrlG {
confirmMode = false
confirmCallback = nil
message = "Quit"
}
redraw()
continue
}
// Handle buffer-local mode handlers
if buf.Mode != "" {
if handler, ok := modeHandlers[buf.Mode]; ok {
if handler(ev, buf, &message) {
buf = buffers[activeBufferIdx]
activeWin.Buffer = buf
redraw()
continue
}
}
}
// Handle read-only buffer restrictions
if buf.ReadOnly && !prefixCx {
switch ev.Key() {
case term.KeyRune:
if ev.Modifiers()&term.ModAlt == 0 {
message = "Buffer is read-only"
redraw()
continue
}
case term.KeyBackspace, term.KeyBackspace2, term.KeyCtrlH:
message = "Buffer is read-only"
redraw()
continue
case term.KeyCtrlD:
message = "Buffer is read-only"
redraw()
continue
case term.KeyCtrlK:
message = "Buffer is read-only"
redraw()
continue
case term.KeyCtrlY:
message = "Buffer is read-only"
redraw()
continue
case term.KeyEnter, term.KeyCtrlJ:
message = "Buffer is read-only"
redraw()
continue
}
}
// Reset consecutive kill tracking for non-kill keys
if ev.Key() != term.KeyCtrlK {
buf.ClearLastKill()
}
// Reset quit warning unless we're in a C-x prefix sequence
if ev.Key() != term.KeyCtrlX && !prefixCx {
quitWarned = false
}
// Handle C-x prefix second key
if prefixCx {
prefixCx = false
switch ev.Key() {
case term.KeyCtrlS:
if err := buf.Save(); err != nil {
if err == errNoFilename {
message = "No file name"
} else {
message = fmt.Sprintf("Error saving: %v", err)
}
} else {
message = fmt.Sprintf("Saved %s", buf.Filename)
}
case term.KeyCtrlC:
anyModified := false
for _, b := range buffers {
if b.Modified {
anyModified = true
break
}
}
if anyModified && !quitWarned {
message = "Modified buffers exist; exit anyway? (C-x C-c to confirm)"
quitWarned = true
} else {
return
}
case term.KeyCtrlB:
// Find existing *Buffer List* or create new one
var blBuf *Buffer
blIdx := -1
for i, b := range buffers {
if b.Filename == "*Buffer List*" {
blBuf = b
blIdx = i
break
}
}
if blBuf == nil {
blBuf = NewBuffer()
blBuf.Filename = "*Buffer List*"
buffers = append(buffers, blBuf)
blIdx = len(buffers) - 1
}
// Update content via shared helper
refreshBufferList()
blBuf.CursorR = 0
blBuf.CursorC = 0
blBuf.ScrollOffset = 0
// Switch to the buffer list buffer
previousBufferIdx = activeBufferIdx
activeBufferIdx = blIdx
buf = buffers[activeBufferIdx]
activeWin.Buffer = buf
activeWin.ScrollOffset = 0
case term.KeyCtrlF:
minibufferMode = true
minibufferPrompt = "Find file: "
minibufferInput = nil
minibufferCursorPos = 0
minibufferCallback = func(input string) {
if input == "" {
message = "No file name specified"
return
}
// Check if the file is already open in an existing buffer
for i, b := range buffers {
if b.Filename == input {
previousBufferIdx = activeBufferIdx
activeBufferIdx = i
buf = buffers[activeBufferIdx]
activeWin.Buffer = buf
activeWin.ScrollOffset = 0
message = fmt.Sprintf("Switch to buffer: %s", input)
return
}
}
// Try to load the file from disk
newBuf, err := NewBufferFromFile(input)
if err != nil {
if os.IsNotExist(err) {
// File doesn't exist: create a new empty buffer with that filename
newBuf = NewBuffer()
newBuf.Filename = input
newBuf.Highlight = NewHighlighter(input)
message = fmt.Sprintf("(New file) %s", input)
} else {
message = fmt.Sprintf("Error: %v", err)
return
}
}
buffers = append(buffers, newBuf)
previousBufferIdx = activeBufferIdx
activeBufferIdx = len(buffers) - 1
buf = buffers[activeBufferIdx]
activeWin.Buffer = buf
activeWin.ScrollOffset = 0
}
message = minibufferPrompt
case term.KeyRune:
switch ev.Rune() {
case 'b':
minibufferMode = true
minibufferPrompt = "Switch to buffer: "
minibufferInput = nil
minibufferCursorPos = 0
minibufferCallback = func(input string) {
if input == "" {
// Switch to previous buffer
previousBufferIdx, activeBufferIdx = activeBufferIdx, previousBufferIdx
buf = buffers[activeBufferIdx]
activeWin.Buffer = buf
activeWin.ScrollOffset = 0
return
}
// Search for existing buffer by name
for i, b := range buffers {
if b.Filename == input {
previousBufferIdx = activeBufferIdx
activeBufferIdx = i
buf = buffers[activeBufferIdx]
activeWin.Buffer = buf
activeWin.ScrollOffset = 0
return
}
}
// Create new empty buffer with that name
newBuf := NewBuffer()
newBuf.Filename = input
buffers = append(buffers, newBuf)
previousBufferIdx = activeBufferIdx
activeBufferIdx = len(buffers) - 1
buf = buffers[activeBufferIdx]
activeWin.Buffer = buf
activeWin.ScrollOffset = 0
}
message = minibufferPrompt
case '2':
// Split current window vertically (top/bottom)
if splitMode == "horizontal" && len(windows) > 1 {
message = "Cannot split vertically while in horizontal split mode"
} else {
newWin := &Window{
Buffer: activeWin.Buffer,
ScrollOffset: activeWin.ScrollOffset,
}
if len(windows) == 1 {
splitMode = "vertical"
}
// Insert new window after the active one
idx := activeWindowIdx + 1
windows = append(windows, nil)
copy(windows[idx+1:], windows[idx:])
windows[idx] = newWin
recalcWindows(windows, screenWidth, screenHeight)
}
case '3':
// Split current window horizontally (side-by-side)
if splitMode == "vertical" && len(windows) > 1 {
message = "Cannot split horizontally while in vertical split mode"
} else {
// Check minimum width: each window needs at least 10 columns,
// plus 1 separator column between each pair of windows.
newCount := len(windows) + 1
availableWidth := screenWidth - (newCount - 1) // subtract separator columns
if availableWidth/newCount < 10 {
message = "Window too narrow to split"
} else {
newWin := &Window{
Buffer: activeWin.Buffer,
ScrollOffset: activeWin.ScrollOffset,
}
if len(windows) == 1 {
splitMode = "horizontal"
}
// Insert new window after the active one
idx := activeWindowIdx + 1
windows = append(windows, nil)
copy(windows[idx+1:], windows[idx:])
windows[idx] = newWin
recalcWindows(windows, screenWidth, screenHeight)
}
}
case 'o':
// Move focus to next window (cycle)
if len(windows) > 1 {
activeWindowIdx = (activeWindowIdx + 1) % len(windows)
activeWin = windows[activeWindowIdx]
buf = activeWin.Buffer
for i, b := range buffers {
if b == activeWin.Buffer {
previousBufferIdx = activeBufferIdx
activeBufferIdx = i
break
}
}
}
case '0':
// Close current window (no-op if only one window)
if len(windows) > 1 {
windows = append(windows[:activeWindowIdx], windows[activeWindowIdx+1:]...)
if activeWindowIdx >= len(windows) {
activeWindowIdx = len(windows) - 1
}
if len(windows) == 1 {
splitMode = "vertical"
}
recalcWindows(windows, screenWidth, screenHeight)
activeWin = windows[activeWindowIdx]
buf = activeWin.Buffer
for i, b := range buffers {
if b == activeWin.Buffer {
previousBufferIdx = activeBufferIdx
activeBufferIdx = i
break
}
}
}
case '1':
// Close all windows except current
if len(windows) > 1 {
windows = []*Window{activeWin}
activeWindowIdx = 0
splitMode = "vertical"
recalcWindows(windows, screenWidth, screenHeight)
}
case 'k':
currentName := buf.Filename
if currentName == "" {
currentName = "[No Name]"
}
minibufferMode = true
minibufferPrompt = fmt.Sprintf("Kill buffer: (default %s) ", currentName)
minibufferInput = nil
minibufferCursorPos = 0
minibufferCallback = func(input string) {
// Find target buffer
targetIdx := activeBufferIdx
if input != "" {
targetIdx = -1
for i, b := range buffers {
if b.Filename == input {
targetIdx = i
break
}
}
if targetIdx == -1 {
message = fmt.Sprintf("No buffer named %s", input)
return
}
}
killBuffer := func() {
killedBuf := buffers[targetIdx]
killedName := killedBuf.Filename
// Remove buffer from list
buffers = append(buffers[:targetIdx], buffers[targetIdx+1:]...)
// If no buffers left, create *scratch*
if len(buffers) == 0 {
scratch := NewBuffer()
scratch.Filename = "*scratch*"
buffers = append(buffers, scratch)
activeBufferIdx = 0
previousBufferIdx = 0
buf = buffers[0]
// Update all windows displaying the killed buffer
for _, w := range windows {
if w.Buffer == killedBuf {
w.Buffer = buf
w.ScrollOffset = 0
}
}
message = fmt.Sprintf("Killed buffer %s", killedName)
refreshBufferList()
return
}
// Adjust activeBufferIdx
if targetIdx == activeBufferIdx {
if activeBufferIdx >= len(buffers) {
activeBufferIdx = len(buffers) - 1
}
} else if targetIdx < activeBufferIdx {
activeBufferIdx--
}
// Adjust previousBufferIdx
if previousBufferIdx == targetIdx {
previousBufferIdx = activeBufferIdx
} else if previousBufferIdx > targetIdx {
previousBufferIdx--
}
if previousBufferIdx >= len(buffers) {
previousBufferIdx = len(buffers) - 1
}
buf = buffers[activeBufferIdx]
// Update all windows displaying the killed buffer
for _, w := range windows {
if w.Buffer == killedBuf {
w.Buffer = buf
w.ScrollOffset = 0
}
}
message = fmt.Sprintf("Killed buffer %s", killedName)
refreshBufferList()
}
// Check if buffer is modified
if buffers[targetIdx].Modified {
message = "Buffer modified; kill anyway? (y/n)"
confirmMode = true
confirmCallback = func(yes bool) {
if yes {
killBuffer()
}
}