-
Notifications
You must be signed in to change notification settings - Fork 1
/
buf.go
131 lines (119 loc) · 2.6 KB
/
buf.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
package nyne
import (
"unicode/utf8"
)
// Buf implements the BufListener interface and runs on opened
// acme buffers
type Buf struct {
id int
file string
win *Win
EventHooks map[Text][]Handler
WinHooks map[Text][]WinHandler
KeyHooks map[rune]Handler
}
// NewBuf constructs an event loop
func NewBuf(id int, file string) *Buf {
return &Buf{
id: id,
file: file,
EventHooks: make(map[Text][]Handler),
WinHooks: make(map[Text][]WinHandler),
KeyHooks: make(map[rune]Handler),
}
}
// File returns the buffers active file
func (b *Buf) File() string {
return b.file
}
//Win returns the active acme Window
func (b *Buf) Win() *Win {
return b.win
}
// Start begins the event listener for the window
func (b *Buf) Start() error {
w, err := OpenWin(b.id, b.file)
if err != nil {
return err
}
b.win = w
// runs hooks for acme 'new' event
go b.winEvent(b.win, Event{Text: New})
stop := make(chan struct{})
defer func() { stop <- struct{}{} }()
events, errs := b.win.EventChan(b.id, b.file, stop)
for {
select {
case event, ok := <-events:
if !ok {
return nil
}
if event.Origin == Keyboard && event.Action == BodyInsert {
w.Lastpoint = event.SelBegin
event, ok = b.keyEvent(event)
} else {
if event.Origin == DelOrigin && event.Action == DelAction {
b.win.WriteEvent(event)
b.win.Close()
return nil
}
event, ok = b.execEvent(event)
}
if !ok {
continue
}
b.win.WriteEvent(event)
for _, h := range event.WriteHooks {
if err := h(event); err != nil {
return err
}
}
// maintain current address after formatting buffer
if event.Text == Put {
body, err := b.win.Body()
if err != nil {
return err
}
if len(body) < w.Lastpoint {
w.Lastpoint = len(body)
}
if err := b.win.SetAddr("#%d", w.Lastpoint); err != nil {
return err
}
if err := b.win.SelectionFromAddr(); err != nil {
return err
}
if err := b.win.Show(); err != nil {
return err
}
}
case err := <-errs:
return err
}
}
}
func (b *Buf) winEvent(w *Win, event Event) {
for _, hook := range b.WinHooks[event.Text] {
hook(w)
}
}
func (b *Buf) keyEvent(event Event) (Event, bool) {
r, _ := utf8.DecodeRune(event.Text.Bytes())
hook, ok := b.KeyHooks[r]
if !ok {
return event, true
}
return hook(event)
}
func (b *Buf) execEvent(event Event) (Event, bool) {
origEvent := event
newEvent := origEvent
ok := true
for _, hook := range b.EventHooks[event.Text] {
newEvent, ok = hook(newEvent)
if !ok {
return origEvent, true
}
}
return newEvent, ok
}