8 // Opposite and undoing events must have opposite values
10 // TextEventInsert repreasents an insertion event
12 // TextEventRemove represents a deletion event
16 // TextEvent holds data for a manipulation on some text that can be undone
17 type TextEvent struct {
27 // ExecuteTextEvent runs a text event
28 func ExecuteTextEvent(t *TextEvent, buf *Buffer) {
29 if t.eventType == TextEventInsert {
30 buf.Insert(t.start, t.text)
31 } else if t.eventType == TextEventRemove {
32 t.text = buf.Remove(t.start, t.end)
36 // UndoTextEvent undoes a text event
37 func UndoTextEvent(t *TextEvent, buf *Buffer) {
38 t.eventType = -t.eventType
39 ExecuteTextEvent(t, buf)
42 // EventHandler executes text manipulations and allows undoing and redoing
43 type EventHandler struct {
49 // NewEventHandler returns a new EventHandler
50 func NewEventHandler(v *View) *EventHandler {
51 eh := new(EventHandler)
58 // Insert creates an insert text event and executes it
59 func (eh *EventHandler) Insert(start int, text string) {
62 eventType: TextEventInsert,
65 end: start + Count(text),
71 // Remove creates a remove text event and executes it
72 func (eh *EventHandler) Remove(start, end int) {
75 eventType: TextEventRemove,
83 // Replace deletes from start to end and replaces it with the given string
84 func (eh *EventHandler) Replace(start, end int, replace string) {
86 eh.Insert(start, replace)
89 // Execute a textevent and add it to the undo stack
90 func (eh *EventHandler) Execute(t *TextEvent) {
91 if eh.redo.Len() > 0 {
95 ExecuteTextEvent(t, eh.v.Buf)
98 // Undo the first event in the undo stack
99 func (eh *EventHandler) Undo() {
106 startTime := t.(*TextEvent).time.UnixNano() / int64(time.Millisecond)
118 if startTime-(te.time.UnixNano()/int64(time.Millisecond)) > undoThreshold {
126 // UndoOneEvent undoes one event
127 func (eh *EventHandler) UndoOneEvent() {
128 // This event should be undone
129 // Pop it off the stack
137 // Modifies the text event
138 UndoTextEvent(te, eh.v.Buf)
140 // Set the cursor in the right place
143 eh.v.Cursor = teCursor
145 // Push it to the redo stack
149 // Redo the first event in the redo stack
150 func (eh *EventHandler) Redo() {
157 startTime := t.(*TextEvent).time.UnixNano() / int64(time.Millisecond)
169 if (te.time.UnixNano()/int64(time.Millisecond))-startTime > undoThreshold {
177 // RedoOneEvent redoes one event
178 func (eh *EventHandler) RedoOneEvent() {
185 // Modifies the text event
186 UndoTextEvent(te, eh.v.Buf)
190 eh.v.Cursor = teCursor