]> git.lizzy.rs Git - micro.git/blob - internal/buffer/eventhandler.go
Synchronize undo and redo chunks
[micro.git] / internal / buffer / eventhandler.go
1 package buffer
2
3 import (
4         "time"
5         "unicode/utf8"
6
7         dmp "github.com/sergi/go-diff/diffmatchpatch"
8         "github.com/zyedidia/micro/internal/config"
9         ulua "github.com/zyedidia/micro/internal/lua"
10         "github.com/zyedidia/micro/internal/screen"
11         luar "layeh.com/gopher-luar"
12 )
13
14 const (
15         // Opposite and undoing events must have opposite values
16
17         // TextEventInsert represents an insertion event
18         TextEventInsert = 1
19         // TextEventRemove represents a deletion event
20         TextEventRemove = -1
21         // TextEventReplace represents a replace event
22         TextEventReplace = 0
23
24         undoThreshold = 1000 // If two events are less than n milliseconds apart, undo both of them
25 )
26
27 // TextEvent holds data for a manipulation on some text that can be undone
28 type TextEvent struct {
29         C Cursor
30
31         EventType int
32         Deltas    []Delta
33         Time      time.Time
34 }
35
36 // A Delta is a change to the buffer
37 type Delta struct {
38         Text  []byte
39         Start Loc
40         End   Loc
41 }
42
43 // ExecuteTextEvent runs a text event
44 func ExecuteTextEvent(t *TextEvent, buf *SharedBuffer) {
45         if t.EventType == TextEventInsert {
46                 for _, d := range t.Deltas {
47                         buf.insert(d.Start, d.Text)
48                 }
49         } else if t.EventType == TextEventRemove {
50                 for i, d := range t.Deltas {
51                         t.Deltas[i].Text = buf.remove(d.Start, d.End)
52                 }
53         } else if t.EventType == TextEventReplace {
54                 for i, d := range t.Deltas {
55                         t.Deltas[i].Text = buf.remove(d.Start, d.End)
56                         buf.insert(d.Start, d.Text)
57                         t.Deltas[i].Start = d.Start
58                         t.Deltas[i].End = Loc{d.Start.X + utf8.RuneCount(d.Text), d.Start.Y}
59                 }
60                 for i, j := 0, len(t.Deltas)-1; i < j; i, j = i+1, j-1 {
61                         t.Deltas[i], t.Deltas[j] = t.Deltas[j], t.Deltas[i]
62                 }
63         }
64 }
65
66 // UndoTextEvent undoes a text event
67 func UndoTextEvent(t *TextEvent, buf *SharedBuffer) {
68         t.EventType = -t.EventType
69         ExecuteTextEvent(t, buf)
70 }
71
72 // EventHandler executes text manipulations and allows undoing and redoing
73 type EventHandler struct {
74         buf       *SharedBuffer
75         cursors   []*Cursor
76         active    int
77         UndoStack *TEStack
78         RedoStack *TEStack
79 }
80
81 // NewEventHandler returns a new EventHandler
82 func NewEventHandler(buf *SharedBuffer, cursors []*Cursor) *EventHandler {
83         eh := new(EventHandler)
84         eh.UndoStack = new(TEStack)
85         eh.RedoStack = new(TEStack)
86         eh.buf = buf
87         eh.cursors = cursors
88         return eh
89 }
90
91 // ApplyDiff takes a string and runs the necessary insertion and deletion events to make
92 // the buffer equal to that string
93 // This means that we can transform the buffer into any string and still preserve undo/redo
94 // through insert and delete events
95 func (eh *EventHandler) ApplyDiff(new string) {
96         differ := dmp.New()
97         diff := differ.DiffMain(string(eh.buf.Bytes()), new, false)
98         loc := eh.buf.Start()
99         for _, d := range diff {
100                 if d.Type == dmp.DiffDelete {
101                         eh.Remove(loc, loc.MoveLA(utf8.RuneCountInString(d.Text), eh.buf.LineArray))
102                 } else {
103                         if d.Type == dmp.DiffInsert {
104                                 eh.Insert(loc, d.Text)
105                         }
106                         loc = loc.MoveLA(utf8.RuneCountInString(d.Text), eh.buf.LineArray)
107                 }
108         }
109 }
110
111 // Insert creates an insert text event and executes it
112 func (eh *EventHandler) Insert(start Loc, textStr string) {
113         text := []byte(textStr)
114         e := &TextEvent{
115                 C:         *eh.cursors[eh.active],
116                 EventType: TextEventInsert,
117                 Deltas:    []Delta{{text, start, Loc{0, 0}}},
118                 Time:      time.Now(),
119         }
120         eh.Execute(e)
121         e.Deltas[0].End = start.MoveLA(utf8.RuneCount(text), eh.buf.LineArray)
122         end := e.Deltas[0].End
123
124         for _, c := range eh.cursors {
125                 move := func(loc Loc) Loc {
126                         if start.Y != end.Y && loc.GreaterThan(start) {
127                                 loc.Y += end.Y - start.Y
128                         } else if loc.Y == start.Y && loc.GreaterEqual(start) {
129                                 loc = loc.MoveLA(utf8.RuneCount(text), eh.buf.LineArray)
130                         }
131                         return loc
132                 }
133                 c.Loc = move(c.Loc)
134                 c.CurSelection[0] = move(c.CurSelection[0])
135                 c.CurSelection[1] = move(c.CurSelection[1])
136                 c.OrigSelection[0] = move(c.OrigSelection[0])
137                 c.OrigSelection[1] = move(c.OrigSelection[1])
138                 c.LastVisualX = c.GetVisualX()
139         }
140 }
141
142 // Remove creates a remove text event and executes it
143 func (eh *EventHandler) Remove(start, end Loc) {
144         e := &TextEvent{
145                 C:         *eh.cursors[eh.active],
146                 EventType: TextEventRemove,
147                 Deltas:    []Delta{{[]byte{}, start, end}},
148                 Time:      time.Now(),
149         }
150         eh.Execute(e)
151
152         for _, c := range eh.cursors {
153                 move := func(loc Loc) Loc {
154                         if start.Y != end.Y && loc.GreaterThan(end) {
155                                 loc.Y -= end.Y - start.Y
156                         } else if loc.Y == end.Y && loc.GreaterEqual(end) {
157                                 loc = loc.MoveLA(-DiffLA(start, end, eh.buf.LineArray), eh.buf.LineArray)
158                         }
159                         return loc
160                 }
161                 c.Loc = move(c.Loc)
162                 c.CurSelection[0] = move(c.CurSelection[0])
163                 c.CurSelection[1] = move(c.CurSelection[1])
164                 c.OrigSelection[0] = move(c.OrigSelection[0])
165                 c.OrigSelection[1] = move(c.OrigSelection[1])
166                 c.LastVisualX = c.GetVisualX()
167         }
168 }
169
170 // MultipleReplace creates an multiple insertions executes them
171 func (eh *EventHandler) MultipleReplace(deltas []Delta) {
172         e := &TextEvent{
173                 C:         *eh.cursors[eh.active],
174                 EventType: TextEventReplace,
175                 Deltas:    deltas,
176                 Time:      time.Now(),
177         }
178         eh.Execute(e)
179 }
180
181 // Replace deletes from start to end and replaces it with the given string
182 func (eh *EventHandler) Replace(start, end Loc, replace string) {
183         eh.Remove(start, end)
184         eh.Insert(start, replace)
185 }
186
187 // Execute a textevent and add it to the undo stack
188 func (eh *EventHandler) Execute(t *TextEvent) {
189         if eh.RedoStack.Len() > 0 {
190                 eh.RedoStack = new(TEStack)
191         }
192         eh.UndoStack.Push(t)
193
194         b, err := config.RunPluginFnBool("onBeforeTextEvent", luar.New(ulua.L, eh.buf), luar.New(ulua.L, t))
195         if err != nil {
196                 screen.TermMessage(err)
197         }
198
199         if !b {
200                 return
201         }
202
203         ExecuteTextEvent(t, eh.buf)
204 }
205
206 // Undo the first event in the undo stack
207 func (eh *EventHandler) Undo() {
208         t := eh.UndoStack.Peek()
209         if t == nil {
210                 return
211         }
212
213         startTime := t.Time.UnixNano() / int64(time.Millisecond)
214         endTime := startTime - (startTime % undoThreshold)
215
216         for {
217                 t = eh.UndoStack.Peek()
218                 if t == nil {
219                         return
220                 }
221
222                 if t.Time.UnixNano()/int64(time.Millisecond) < endTime {
223                         return
224                 }
225
226                 eh.UndoOneEvent()
227         }
228 }
229
230 // UndoOneEvent undoes one event
231 func (eh *EventHandler) UndoOneEvent() {
232         // This event should be undone
233         // Pop it off the stack
234         t := eh.UndoStack.Pop()
235         if t == nil {
236                 return
237         }
238
239         // Undo it
240         // Modifies the text event
241         UndoTextEvent(t, eh.buf)
242
243         // Set the cursor in the right place
244         teCursor := t.C
245         if teCursor.Num >= 0 && teCursor.Num < len(eh.cursors) {
246                 t.C = *eh.cursors[teCursor.Num]
247                 eh.cursors[teCursor.Num].Goto(teCursor)
248         } else {
249                 teCursor.Num = -1
250         }
251
252         // Push it to the redo stack
253         eh.RedoStack.Push(t)
254 }
255
256 // Redo the first event in the redo stack
257 func (eh *EventHandler) Redo() {
258         t := eh.RedoStack.Peek()
259         if t == nil {
260                 return
261         }
262
263         startTime := t.Time.UnixNano() / int64(time.Millisecond)
264         endTime := startTime - (startTime % undoThreshold) + undoThreshold
265
266         for {
267                 t = eh.RedoStack.Peek()
268                 if t == nil {
269                         return
270                 }
271
272                 if t.Time.UnixNano()/int64(time.Millisecond) > endTime {
273                         return
274                 }
275
276                 eh.RedoOneEvent()
277         }
278 }
279
280 // RedoOneEvent redoes one event
281 func (eh *EventHandler) RedoOneEvent() {
282         t := eh.RedoStack.Pop()
283         if t == nil {
284                 return
285         }
286
287         // Modifies the text event
288         UndoTextEvent(t, eh.buf)
289
290         teCursor := t.C
291         if teCursor.Num >= 0 && teCursor.Num < len(eh.cursors) {
292                 t.C = *eh.cursors[teCursor.Num]
293                 eh.cursors[teCursor.Num].Goto(teCursor)
294         } else {
295                 teCursor.Num = -1
296         }
297
298         eh.UndoStack.Push(t)
299 }