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(buf *Buffer) *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.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 undoThreshold := int64(settings["undothreshold"].(float64))
119 if startTime-(te.time.UnixNano()/int64(time.Millisecond)) > undoThreshold {
127 // UndoOneEvent undoes one event
128 func (eh *EventHandler) UndoOneEvent() {
129 // This event should be undone
130 // Pop it off the stack
138 // Modifies the text event
139 UndoTextEvent(te, eh.buf)
141 // Set the cursor in the right place
144 eh.buf.Cursor = teCursor
146 // Push it to the redo stack
150 // Redo the first event in the redo stack
151 func (eh *EventHandler) Redo() {
158 startTime := t.(*TextEvent).time.UnixNano() / int64(time.Millisecond)
170 undoThreshold := int64(settings["undothreshold"].(float64))
171 if (te.time.UnixNano()/int64(time.Millisecond))-startTime > undoThreshold {
179 // RedoOneEvent redoes one event
180 func (eh *EventHandler) RedoOneEvent() {
187 // Modifies the text event
188 UndoTextEvent(te, eh.buf)
192 eh.buf.Cursor = teCursor