Debian Codegraph @

internal/buffer/eventhandler.go

raw
1 package buffer
2
3 import (
4 "bytes"
5 "time"
6
7 dmp "github.com/sergi/go-diff/diffmatchpatch"
8 "github.com/zyedidia/micro/v2/internal/config"
9 ulua "github.com/zyedidia/micro/v2/internal/lua"
10 "github.com/zyedidia/micro/v2/internal/screen"
11 "github.com/zyedidia/micro/v2/internal/util"
12 luar "layeh.com/gopher-luar"
13 )
14
15 const (
16 // Opposite and undoing events must have opposite values
17
18 // TextEventInsert represents an insertion event
19 TextEventInsert = 1
20 // TextEventRemove represents a deletion event
21 TextEventRemove = -1
22 // TextEventReplace represents a replace event
23 TextEventReplace = 0
24
25 undoThreshold = 1000 // If two events are less than n milliseconds apart, undo both of them
26 )
27
28 // TextEvent holds data for a manipulation on some text that can be undone
29 type TextEvent struct {
30 C Cursor
31
32 EventType int
33 Deltas []Delta
34 Time time.Time
35 }
36
37 // A Delta is a change to the buffer
38 type Delta struct {
39 Text []byte
40 Start Loc
41 End Loc
42 }
43
44 // DoTextEvent runs a text event
45 func (eh *EventHandler) DoTextEvent(t *TextEvent, useUndo bool) {
46 oldl := eh.buf.LinesNum()
47
48 if useUndo {
49 eh.Execute(t)
50 } else {
51 ExecuteTextEvent(t, eh.buf)
52 }
53
54 if len(t.Deltas) != 1 {
55 return
56 }
57
58 text := t.Deltas[0].Text
59 start := t.Deltas[0].Start
60 lastnl := -1
61 var endX int
62 var textX int
63 if t.EventType == TextEventInsert {
64 linecount := eh.buf.LinesNum() - oldl
65 textcount := util.CharacterCount(text)
66 lastnl = bytes.LastIndex(text, []byte{'\n'})
67 if lastnl >= 0 {
68 endX = util.CharacterCount(text[lastnl+1:])
69 textX = endX
70 } else {
71 endX = start.X + textcount
72 textX = textcount
73 }
74 t.Deltas[0].End = clamp(Loc{endX, start.Y + linecount}, eh.buf.LineArray)
75 }
76 end := t.Deltas[0].End
77
78 for _, c := range eh.cursors {
79 move := func(loc Loc) Loc {
80 if t.EventType == TextEventInsert {
81 if start.Y != loc.Y && loc.GreaterThan(start) {
82 loc.Y += end.Y - start.Y
83 } else if loc.Y == start.Y && loc.GreaterEqual(start) {
84 loc.Y += end.Y - start.Y
85 if lastnl >= 0 {
86 loc.X += textX - start.X
87 } else {
88 loc.X += textX
89 }
90 }
91 return loc
92 } else {
93 if loc.Y != end.Y && loc.GreaterThan(end) {
94 loc.Y -= end.Y - start.Y
95 } else if loc.Y == end.Y && loc.GreaterEqual(end) {
96 loc = loc.MoveLA(-DiffLA(start, end, eh.buf.LineArray), eh.buf.LineArray)
97 }
98 return loc
99 }
100 }
101 c.Loc = move(c.Loc)
102 c.CurSelection[0] = move(c.CurSelection[0])
103 c.CurSelection[1] = move(c.CurSelection[1])
104 c.OrigSelection[0] = move(c.OrigSelection[0])
105 c.OrigSelection[1] = move(c.OrigSelection[1])
106 c.Relocate()
107 c.StoreVisualX()
108 }
109
110 if useUndo {
111 eh.updateTrailingWs(t)
112 }
113 }
114
115 // ExecuteTextEvent runs a text event
116 func ExecuteTextEvent(t *TextEvent, buf *SharedBuffer) {
117 if t.EventType == TextEventInsert {
118 for _, d := range t.Deltas {
119 buf.insert(d.Start, d.Text)
120 }
121 } else if t.EventType == TextEventRemove {
122 for i, d := range t.Deltas {
123 t.Deltas[i].Text = buf.remove(d.Start, d.End)
124 }
125 } else if t.EventType == TextEventReplace {
126 for i, d := range t.Deltas {
127 t.Deltas[i].Text = buf.remove(d.Start, d.End)
128 buf.insert(d.Start, d.Text)
129 t.Deltas[i].Start = d.Start
130 t.Deltas[i].End = Loc{d.Start.X + util.CharacterCount(d.Text), d.Start.Y}
131 }
132 for i, j := 0, len(t.Deltas)-1; i < j; i, j = i+1, j-1 {
133 t.Deltas[i], t.Deltas[j] = t.Deltas[j], t.Deltas[i]
134 }
135 }
136 }
137
138 // UndoTextEvent undoes a text event
139 func (eh *EventHandler) UndoTextEvent(t *TextEvent) {
140 t.EventType = -t.EventType
141 eh.DoTextEvent(t, false)
142 }
143
144 // EventHandler executes text manipulations and allows undoing and redoing
145 type EventHandler struct {
146 buf *SharedBuffer
147 cursors []*Cursor
148 active int
149 UndoStack *TEStack
150 RedoStack *TEStack
151 }
152
153 // NewEventHandler returns a new EventHandler
154 func NewEventHandler(buf *SharedBuffer, cursors []*Cursor) *EventHandler {
155 eh := new(EventHandler)
156 eh.UndoStack = new(TEStack)
157 eh.RedoStack = new(TEStack)
158 eh.buf = buf
159 eh.cursors = cursors
160 return eh
161 }
162
163 // ApplyDiff takes a string and runs the necessary insertion and deletion events to make
164 // the buffer equal to that string
165 // This means that we can transform the buffer into any string and still preserve undo/redo
166 // through insert and delete events
167 func (eh *EventHandler) ApplyDiff(new string) {
168 differ := dmp.New()
169 diff := differ.DiffMain(string(eh.buf.Bytes()), new, false)
170 loc := eh.buf.Start()
171 for _, d := range diff {
172 if d.Type == dmp.DiffDelete {
173 eh.Remove(loc, loc.MoveLA(util.CharacterCountInString(d.Text), eh.buf.LineArray))
174 } else {
175 if d.Type == dmp.DiffInsert {
176 eh.Insert(loc, d.Text)
177 }
178 loc = loc.MoveLA(util.CharacterCountInString(d.Text), eh.buf.LineArray)
179 }
180 }
181 }
182
183 // Insert creates an insert text event and executes it
184 func (eh *EventHandler) Insert(start Loc, textStr string) {
185 text := []byte(textStr)
186 eh.InsertBytes(start, text)
187 }
188
189 // InsertBytes creates an insert text event and executes it
190 func (eh *EventHandler) InsertBytes(start Loc, text []byte) {
191 if len(text) == 0 {
192 return
193 }
194 start = clamp(start, eh.buf.LineArray)
195 e := &TextEvent{
196 C: *eh.cursors[eh.active],
197 EventType: TextEventInsert,
198 Deltas: []Delta{{text, start, Loc{0, 0}}},
199 Time: time.Now(),
200 }
201 eh.DoTextEvent(e, true)
202 }
203
204 // Remove creates a remove text event and executes it
205 func (eh *EventHandler) Remove(start, end Loc) {
206 if start == end {
207 return
208 }
209 start = clamp(start, eh.buf.LineArray)
210 end = clamp(end, eh.buf.LineArray)
211 e := &TextEvent{
212 C: *eh.cursors[eh.active],
213 EventType: TextEventRemove,
214 Deltas: []Delta{{[]byte{}, start, end}},
215 Time: time.Now(),
216 }
217 eh.DoTextEvent(e, true)
218 }
219
220 // MultipleReplace creates an multiple insertions executes them
221 func (eh *EventHandler) MultipleReplace(deltas []Delta) {
222 e := &TextEvent{
223 C: *eh.cursors[eh.active],
224 EventType: TextEventReplace,
225 Deltas: deltas,
226 Time: time.Now(),
227 }
228 eh.Execute(e)
229 }
230
231 // Replace deletes from start to end and replaces it with the given string
232 func (eh *EventHandler) Replace(start, end Loc, replace string) {
233 eh.Remove(start, end)
234 eh.Insert(start, replace)
235 }
236
237 // Execute a textevent and add it to the undo stack
238 func (eh *EventHandler) Execute(t *TextEvent) {
239 if eh.RedoStack.Len() > 0 {
240 eh.RedoStack = new(TEStack)
241 }
242 eh.UndoStack.Push(t)
243
244 b, err := config.RunPluginFnBool(nil, "onBeforeTextEvent", luar.New(ulua.L, eh.buf), luar.New(ulua.L, t))
245 if err != nil {
246 screen.TermMessage(err)
247 }
248
249 if !b {
250 return
251 }
252
253 ExecuteTextEvent(t, eh.buf)
254 }
255
256 // Undo the first event in the undo stack. Returns false if the stack is empty.
257 func (eh *EventHandler) Undo() bool {
258 t := eh.UndoStack.Peek()
259 if t == nil {
260 return false
261 }
262
263 startTime := t.Time.UnixNano() / int64(time.Millisecond)
264 endTime := startTime - (startTime % undoThreshold)
265
266 for {
267 t = eh.UndoStack.Peek()
268 if t == nil {
269 break
270 }
271
272 if t.Time.UnixNano()/int64(time.Millisecond) < endTime {
273 break
274 }
275
276 eh.UndoOneEvent()
277 }
278 return true
279 }
280
281 // UndoOneEvent undoes one event
282 func (eh *EventHandler) UndoOneEvent() {
283 // This event should be undone
284 // Pop it off the stack
285 t := eh.UndoStack.Pop()
286 if t == nil {
287 return
288 }
289 // Undo it
290 // Modifies the text event
291 eh.UndoTextEvent(t)
292
293 // Set the cursor in the right place
294 if t.C.Num >= 0 && t.C.Num < len(eh.cursors) {
295 eh.cursors[t.C.Num].Goto(t.C)
296 eh.cursors[t.C.Num].NewTrailingWsY = t.C.NewTrailingWsY
297 }
298
299 // Push it to the redo stack
300 eh.RedoStack.Push(t)
301 }
302
303 // Redo the first event in the redo stack. Returns false if the stack is empty.
304 func (eh *EventHandler) Redo() bool {
305 t := eh.RedoStack.Peek()
306 if t == nil {
307 return false
308 }
309
310 startTime := t.Time.UnixNano() / int64(time.Millisecond)
311 endTime := startTime - (startTime % undoThreshold) + undoThreshold
312
313 for {
314 t = eh.RedoStack.Peek()
315 if t == nil {
316 break
317 }
318
319 if t.Time.UnixNano()/int64(time.Millisecond) > endTime {
320 break
321 }
322
323 eh.RedoOneEvent()
324 }
325 return true
326 }
327
328 // RedoOneEvent redoes one event
329 func (eh *EventHandler) RedoOneEvent() {
330 t := eh.RedoStack.Pop()
331 if t == nil {
332 return
333 }
334
335 if t.C.Num >= 0 && t.C.Num < len(eh.cursors) {
336 eh.cursors[t.C.Num].Goto(t.C)
337 eh.cursors[t.C.Num].NewTrailingWsY = t.C.NewTrailingWsY
338 }
339
340 // Modifies the text event
341 eh.UndoTextEvent(t)
342
343 eh.UndoStack.Push(t)
344 }
345
346 // updateTrailingWs updates the cursor's trailing whitespace status after a text event
347 func (eh *EventHandler) updateTrailingWs(t *TextEvent) {
348 if len(t.Deltas) != 1 {
349 return
350 }
351 text := t.Deltas[0].Text
352 start := t.Deltas[0].Start
353 end := t.Deltas[0].End
354
355 c := eh.cursors[eh.active]
356 isEol := func(loc Loc) bool {
357 return loc.X == util.CharacterCount(eh.buf.LineBytes(loc.Y))
358 }
359 if t.EventType == TextEventInsert && c.Loc == end && isEol(end) {
360 var addedTrailingWs bool
361 addedAfterWs := false
362 addedWsOnly := false
363 if start.Y == end.Y {
364 addedTrailingWs = util.HasTrailingWhitespace(text)
365 addedWsOnly = util.IsBytesWhitespace(text)
366 addedAfterWs = start.X > 0 && util.IsWhitespace(c.buf.RuneAt(Loc{start.X - 1, start.Y}))
367 } else {
368 lastnl := bytes.LastIndex(text, []byte{'\n'})
369 addedTrailingWs = util.HasTrailingWhitespace(text[lastnl+1:])
370 }
371
372 if addedTrailingWs && !(addedAfterWs && addedWsOnly) {
373 c.NewTrailingWsY = c.Y
374 } else if !addedTrailingWs {
375 c.NewTrailingWsY = -1
376 }
377 } else if t.EventType == TextEventRemove && c.Loc == start && isEol(start) {
378 removedAfterWs := util.HasTrailingWhitespace(eh.buf.LineBytes(start.Y))
379 var removedWsOnly bool
380 if start.Y == end.Y {
381 removedWsOnly = util.IsBytesWhitespace(text)
382 } else {
383 firstnl := bytes.Index(text, []byte{'\n'})
384 removedWsOnly = util.IsBytesWhitespace(text[:firstnl])
385 }
386
387 if removedAfterWs && !removedWsOnly {
388 c.NewTrailingWsY = c.Y
389 } else if !removedAfterWs {
390 c.NewTrailingWsY = -1
391 }
392 } else if c.NewTrailingWsY != -1 && start.Y != end.Y && c.Loc.GreaterThan(start) &&
393 ((t.EventType == TextEventInsert && c.Y == c.NewTrailingWsY+(end.Y-start.Y)) ||
394 (t.EventType == TextEventRemove && c.Y == c.NewTrailingWsY-(end.Y-start.Y))) {
395 // The cursor still has its new trailingws
396 // but its line number was shifted by insert or remove of lines above
397 c.NewTrailingWsY = c.Y
398 }
399 }