-
Notifications
You must be signed in to change notification settings - Fork 6
/
undo.go
68 lines (58 loc) · 1.08 KB
/
undo.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
package readline
import (
"github.com/ergochat/readline/internal/ringbuf"
)
type undoEntry struct {
pos int
buf []rune
}
// nil receiver is a valid no-op object
type opUndo struct {
op *operation
stack ringbuf.Buffer[undoEntry]
}
func newOpUndo(op *operation) *opUndo {
o := &opUndo{op: op}
o.stack.Initialize(32, 64)
o.init()
return o
}
func (o *opUndo) add() {
if o == nil {
return
}
top, success := o.stack.Pop()
buf, pos, changed := o.op.buf.CopyForUndo(top.buf) // if !success, top.buf is nil
newEntry := undoEntry{pos: pos, buf: buf}
if !success {
o.stack.Add(newEntry)
} else if !changed {
o.stack.Add(newEntry) // update cursor position
} else {
o.stack.Add(top)
o.stack.Add(newEntry)
}
}
func (o *opUndo) undo() {
if o == nil {
return
}
top, success := o.stack.Pop()
if !success {
return
}
o.op.buf.Restore(top.buf, top.pos)
o.op.buf.Refresh(nil)
}
func (o *opUndo) init() {
if o == nil {
return
}
buf, pos, _ := o.op.buf.CopyForUndo(nil)
initialEntry := undoEntry{
pos: pos,
buf: buf,
}
o.stack.Clear()
o.stack.Add(initialEntry)
}