]> git.lizzy.rs Git - micro.git/blob - internal/buffer/eventhandler.go
Merge pull request #1252 from SunflowerFuchs/patch-1
[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         eh.InsertBytes(start, text)
115 }
116
117 // InsertBytes creates an insert text event and executes it
118 func (eh *EventHandler) InsertBytes(start Loc, text []byte) {
119         e := &TextEvent{
120                 C:         *eh.cursors[eh.active],
121                 EventType: TextEventInsert,
122                 Deltas:    []Delta{{text, start, Loc{0, 0}}},
123                 Time:      time.Now(),
124         }
125         eh.Execute(e)
126         e.Deltas[0].End = start.MoveLA(utf8.RuneCount(text), eh.buf.LineArray)
127         end := e.Deltas[0].End
128
129         for _, c := range eh.cursors {
130                 move := func(loc Loc) Loc {
131                         if start.Y != end.Y && loc.GreaterThan(start) {
132                                 loc.Y += end.Y - start.Y
133                         } else if loc.Y == start.Y && loc.GreaterEqual(start) {
134                                 loc = loc.MoveLA(utf8.RuneCount(text), eh.buf.LineArray)
135                         }
136                         return loc
137                 }
138                 c.Loc = move(c.Loc)
139                 c.CurSelection[0] = move(c.CurSelection[0])
140                 c.CurSelection[1] = move(c.CurSelection[1])
141                 c.OrigSelection[0] = move(c.OrigSelection[0])
142                 c.OrigSelection[1] = move(c.OrigSelection[1])
143                 c.LastVisualX = c.GetVisualX()
144         }
145 }
146
147 // Remove creates a remove text event and executes it
148 func (eh *EventHandler) Remove(start, end Loc) {
149         e := &TextEvent{
150                 C:         *eh.cursors[eh.active],
151                 EventType: TextEventRemove,
152                 Deltas:    []Delta{{[]byte{}, start, end}},
153                 Time:      time.Now(),
154         }
155         eh.Execute(e)
156
157         for _, c := range eh.cursors {
158                 move := func(loc Loc) Loc {
159                         if start.Y != end.Y && loc.GreaterThan(end) {
160                                 loc.Y -= end.Y - start.Y
161                         } else if loc.Y == end.Y && loc.GreaterEqual(end) {
162                                 loc = loc.MoveLA(-DiffLA(start, end, eh.buf.LineArray), eh.buf.LineArray)
163                         }
164                         return loc
165                 }
166                 c.Loc = move(c.Loc)
167                 c.CurSelection[0] = move(c.CurSelection[0])
168                 c.CurSelection[1] = move(c.CurSelection[1])
169                 c.OrigSelection[0] = move(c.OrigSelection[0])
170                 c.OrigSelection[1] = move(c.OrigSelection[1])
171                 c.LastVisualX = c.GetVisualX()
172         }
173 }
174
175 // MultipleReplace creates an multiple insertions executes them
176 func (eh *EventHandler) MultipleReplace(deltas []Delta) {
177         e := &TextEvent{
178                 C:         *eh.cursors[eh.active],
179                 EventType: TextEventReplace,
180                 Deltas:    deltas,
181                 Time:      time.Now(),
182         }
183         eh.Execute(e)
184 }
185
186 // Replace deletes from start to end and replaces it with the given string
187 func (eh *EventHandler) Replace(start, end Loc, replace string) {
188         eh.Remove(start, end)
189         eh.Insert(start, replace)
190 }
191
192 // Execute a textevent and add it to the undo stack
193 func (eh *EventHandler) Execute(t *TextEvent) {
194         if eh.RedoStack.Len() > 0 {
195                 eh.RedoStack = new(TEStack)
196         }
197         eh.UndoStack.Push(t)
198
199         b, err := config.RunPluginFnBool("onBeforeTextEvent", luar.New(ulua.L, eh.buf), luar.New(ulua.L, t))
200         if err != nil {
201                 screen.TermMessage(err)
202         }
203
204         if !b {
205                 return
206         }
207
208         ExecuteTextEvent(t, eh.buf)
209 }
210
211 // Undo the first event in the undo stack
212 func (eh *EventHandler) Undo() {
213         t := eh.UndoStack.Peek()
214         if t == nil {
215                 return
216         }
217
218         startTime := t.Time.UnixNano() / int64(time.Millisecond)
219         endTime := startTime - (startTime % undoThreshold)
220
221         for {
222                 t = eh.UndoStack.Peek()
223                 if t == nil {
224                         return
225                 }
226
227                 if t.Time.UnixNano()/int64(time.Millisecond) < endTime {
228                         return
229                 }
230
231                 eh.UndoOneEvent()
232         }
233 }
234
235 // UndoOneEvent undoes one event
236 func (eh *EventHandler) UndoOneEvent() {
237         // This event should be undone
238         // Pop it off the stack
239         t := eh.UndoStack.Pop()
240         if t == nil {
241                 return
242         }
243
244         // Undo it
245         // Modifies the text event
246         UndoTextEvent(t, eh.buf)
247
248         // Set the cursor in the right place
249         teCursor := t.C
250         if teCursor.Num >= 0 && teCursor.Num < len(eh.cursors) {
251                 t.C = *eh.cursors[teCursor.Num]
252                 eh.cursors[teCursor.Num].Goto(teCursor)
253         } else {
254                 teCursor.Num = -1
255         }
256
257         // Push it to the redo stack
258         eh.RedoStack.Push(t)
259 }
260
261 // Redo the first event in the redo stack
262 func (eh *EventHandler) Redo() {
263         t := eh.RedoStack.Peek()
264         if t == nil {
265                 return
266         }
267
268         startTime := t.Time.UnixNano() / int64(time.Millisecond)
269         endTime := startTime - (startTime % undoThreshold) + undoThreshold
270
271         for {
272                 t = eh.RedoStack.Peek()
273                 if t == nil {
274                         return
275                 }
276
277                 if t.Time.UnixNano()/int64(time.Millisecond) > endTime {
278                         return
279                 }
280
281                 eh.RedoOneEvent()
282         }
283 }
284
285 // RedoOneEvent redoes one event
286 func (eh *EventHandler) RedoOneEvent() {
287         t := eh.RedoStack.Pop()
288         if t == nil {
289                 return
290         }
291
292         // Modifies the text event
293         UndoTextEvent(t, eh.buf)
294
295         teCursor := t.C
296         if teCursor.Num >= 0 && teCursor.Num < len(eh.cursors) {
297                 t.C = *eh.cursors[teCursor.Num]
298                 eh.cursors[teCursor.Num].Goto(teCursor)
299         } else {
300                 teCursor.Num = -1
301         }
302
303         eh.UndoStack.Push(t)
304 }