Skip to content

Commit

Permalink
Implemented redo by sharing @past_lines between undo and redo
Browse files Browse the repository at this point in the history
  • Loading branch information
verdy89 committed May 25, 2024
1 parent 9e0d6ad commit a28ab63
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 10 deletions.
33 changes: 25 additions & 8 deletions lib/reline/line_editor.rb
Original file line number Diff line number Diff line change
Expand Up @@ -250,7 +250,8 @@ def reset_variables(prompt = '', encoding:)
@resized = false
@cache = {}
@rendered_screen = RenderedScreen.new(base_y: 0, lines: [], cursor_y: 0)
@past_lines = []
@past_lines = [[[""], 0, 0]]
@position = 0
@undoing = false
reset_line
end
Expand Down Expand Up @@ -1137,7 +1138,10 @@ def input_key(key)
@completion_journey_state = nil
end

push_past_lines unless @undoing
unless @undoing
@past_lines = @past_lines[0..@position]
push_past_lines
end
@undoing = false

if @in_pasting
Expand All @@ -1161,8 +1165,11 @@ def save_old_buffer
end

def push_past_lines
if @old_buffer_of_lines != @buffer_of_lines
@past_lines.push([@old_buffer_of_lines, @old_byte_pointer, @old_line_index])
if @old_buffer_of_lines == @buffer_of_lines
@past_lines[-1] = [@buffer_of_lines.dup, @byte_pointer, @line_index]
else
@position += 1
@past_lines.push([@buffer_of_lines.dup, @byte_pointer, @line_index])
end
trim_past_lines
end
Expand All @@ -1171,6 +1178,7 @@ def push_past_lines
def trim_past_lines
if @past_lines.size > MAX_PAST_LINES
@past_lines.shift
@position -= 1
end
end

Expand Down Expand Up @@ -2529,13 +2537,22 @@ def finish
end

private def undo(_key)
return if @past_lines.empty?
@undoing = true

return if @position <= 0

@position -= 1
target_lines, target_cursor_x, target_cursor_y = @past_lines[@position]
set_current_lines(target_lines.dup, target_cursor_x, target_cursor_y)
end

private def redo(_key)
@undoing = true

target_lines, target_cursor_x, target_cursor_y = @past_lines.last
set_current_lines(target_lines, target_cursor_x, target_cursor_y)
return if @position >= @past_lines.size - 1

@past_lines.pop
@position += 1
target_lines, target_cursor_x, target_cursor_y = @past_lines[@position]
set_current_lines(target_lines.dup, target_cursor_x, target_cursor_y)
end
end
4 changes: 2 additions & 2 deletions test/reline/test_key_actor_emacs.rb
Original file line number Diff line number Diff line change
Expand Up @@ -1498,7 +1498,7 @@ def test_undo_with_multiline
end

def test_undo_with_many_times
str = "a" + "b" * 100
str = "a" + "b" * 99
input_keys(str, false)
100.times { input_keys("\C-_", false) }
assert_line_around_cursor('a', '')
Expand Down Expand Up @@ -1598,7 +1598,7 @@ def test_redo_with_multiline
end

def test_redo_with_many_times
str = "a" + "b" * 99 + "c"
str = "a" + "b" * 98 + "c"
input_keys(str, false)
100.times { input_keys("\C-_", false) }
assert_line_around_cursor('a', '')
Expand Down

0 comments on commit a28ab63

Please sign in to comment.