Skip to content
Kward Search API index

Class: Kward::PromptInterface::EditorUndoHistory

Inherits:
Object
  • Object
show all
Defined in:
lib/kward/prompt_interface/editor/undo_history.rb

Overview

Bounded undo/redo history for reversible edits and whole-buffer snapshots.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(limit: 100, undo_stack: [], redo_stack: []) ⇒ EditorUndoHistory

Returns a new instance of EditorUndoHistory.



11
12
13
14
15
# File 'lib/kward/prompt_interface/editor/undo_history.rb', line 11

def initialize(limit: 100, undo_stack: [], redo_stack: [])
  @limit = limit
  @undo_stack = undo_stack
  @redo_stack = redo_stack
end

Instance Attribute Details

#redo_stack ⇒ Object (readonly)

Returns the value of attribute redo_stack.



9
10
11
# File 'lib/kward/prompt_interface/editor/undo_history.rb', line 9

def redo_stack
  @redo_stack
end

#undo_stack ⇒ Object (readonly)

Returns the value of attribute undo_stack.



9
10
11
# File 'lib/kward/prompt_interface/editor/undo_history.rb', line 9

def undo_stack
  @undo_stack
end

Instance Method Details

#apply(entry, buffer) ⇒ Object



31
32
33
34
35
36
37
38
39
40
41
# File 'lib/kward/prompt_interface/editor/undo_history.rb', line 31

def apply(entry, buffer)
  if (edits = entry[:edits])
    inverse = []
    apply_edits(edits, buffer) { |edit| inverse << edit }
    { edits: inverse.reverse.freeze }
  else
    previous = buffer.text.dup
    buffer.text = entry[:buffer].to_s
    { buffer: previous }
  end
end

#preserve_targets(text) ⇒ Object

An untracked edit must not invalidate the deltas at either end of history. Preserve the same targets that snapshots would have restored.



45
46
47
48
49
50
51
52
53
54
# File 'lib/kward/prompt_interface/editor/undo_history.rb', line 45

def preserve_targets(text)
  [@undo_stack, @redo_stack].each do |stack|
    entry = stack.last
    next unless entry&.key?(:edits)

    buffer = EditorBuffer.new(text)
    apply_edits(entry[:edits], buffer)
    stack[-1] = entry.except(:edits).merge(buffer: buffer.text)
  end
end

#push(snapshot) ⇒ Object



17
18
19
20
21
# File 'lib/kward/prompt_interface/editor/undo_history.rb', line 17

def push(snapshot)
  @undo_stack << snapshot
  trim(@undo_stack)
  @redo_stack.clear
end

#redo(&restore) ⇒ Object



27
28
29
# File 'lib/kward/prompt_interface/editor/undo_history.rb', line 27

def redo(&restore)
  transfer(@redo_stack, @undo_stack, &restore)
end

#undo(&restore) ⇒ Object



23
24
25
# File 'lib/kward/prompt_interface/editor/undo_history.rb', line 23

def undo(&restore)
  transfer(@undo_stack, @redo_stack, &restore)
end