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 {
28 // ExecuteTextEvent runs a text event
29 func ExecuteTextEvent(t *TextEvent) {
30 if t.eventType == TextEventInsert {
31 t.buf.Insert(t.start, t.text)
32 } else if t.eventType == TextEventRemove {
33 t.text = t.buf.Remove(t.start, t.end)
37 // UndoTextEvent undoes a text event
38 func UndoTextEvent(t *TextEvent) {
39 t.eventType = -t.eventType
43 // EventHandler executes text manipulations and allows undoing and redoing
44 type EventHandler struct {
50 // NewEventHandler returns a new EventHandler
51 func NewEventHandler(v *View) *EventHandler {
52 eh := new(EventHandler)
59 // Insert creates an insert text event and executes it
60 func (eh *EventHandler) Insert(start int, text string) {
63 eventType: TextEventInsert,
66 end: start + Count(text),
73 // Remove creates a remove text event and executes it
74 func (eh *EventHandler) Remove(start, end int) {
77 eventType: TextEventRemove,
86 // Replace deletes from start to end and replaces it with the given string
87 func (eh *EventHandler) Replace(start, end int, replace string) {
89 eh.Insert(start, replace)
92 // Execute a textevent and add it to the undo stack
93 func (eh *EventHandler) Execute(t *TextEvent) {
94 if eh.redo.Len() > 0 {
101 // Undo the first event in the undo stack
102 func (eh *EventHandler) Undo() {
109 startTime := t.(*TextEvent).time.UnixNano() / int64(time.Millisecond)
121 if startTime-(te.time.UnixNano()/int64(time.Millisecond)) > undoThreshold {
129 // UndoOneEvent undoes one event
130 func (eh *EventHandler) UndoOneEvent() {
131 // This event should be undone
132 // Pop it off the stack
140 // Modifies the text event
143 // Set the cursor in the right place
146 eh.v.cursor = teCursor
148 // Push it to the redo stack
152 // Redo the first event in the redo stack
153 func (eh *EventHandler) Redo() {
160 startTime := t.(*TextEvent).time.UnixNano() / int64(time.Millisecond)
172 if (te.time.UnixNano()/int64(time.Millisecond))-startTime > undoThreshold {
180 // RedoOneEvent redoes one event
181 func (eh *EventHandler) RedoOneEvent() {
188 // Modifies the text event
193 eh.v.cursor = teCursor