2019-05-03 06:17:27 +08:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
2013-03-06 15:52:24 +08:00
|
|
|
# this class is used to track changes to an arbitrary buffer
|
2013-02-06 03:16:51 +08:00
|
|
|
|
|
|
|
class ContentBuffer
|
|
|
|
def initialize(initial_content)
|
|
|
|
@initial_content = initial_content
|
|
|
|
@lines = @initial_content.split("\n")
|
|
|
|
end
|
|
|
|
|
|
|
|
def apply_transform!(transform)
|
|
|
|
start_row = transform[:start][:row]
|
|
|
|
start_col = transform[:start][:col]
|
|
|
|
finish_row = transform[:finish][:row] if transform[:finish]
|
|
|
|
finish_col = transform[:finish][:col] if transform[:finish]
|
|
|
|
text = transform[:text]
|
|
|
|
|
|
|
|
if transform[:operation] == :delete
|
2013-02-26 00:42:20 +08:00
|
|
|
# fix first line
|
|
|
|
|
|
|
|
l = @lines[start_row]
|
2013-02-06 03:16:51 +08:00
|
|
|
l = l[0...start_col]
|
2013-02-26 00:42:20 +08:00
|
|
|
|
2013-02-06 03:16:51 +08:00
|
|
|
if (finish_row == start_row)
|
|
|
|
l << @lines[start_row][finish_col..-1]
|
|
|
|
@lines[start_row] = l
|
|
|
|
return
|
|
|
|
end
|
|
|
|
|
|
|
|
@lines[start_row] = l
|
|
|
|
|
2013-02-26 00:42:20 +08:00
|
|
|
# remove middle lines
|
2013-02-06 03:16:51 +08:00
|
|
|
(finish_row - start_row).times { l = @lines.delete_at start_row + 1 }
|
|
|
|
|
2013-02-26 00:42:20 +08:00
|
|
|
# fix last line
|
2013-02-06 03:16:51 +08:00
|
|
|
@lines[start_row] << @lines[finish_row][finish_col - 1..-1]
|
|
|
|
end
|
|
|
|
|
|
|
|
if transform[:operation] == :insert
|
|
|
|
@lines[start_row].insert(start_col, text)
|
2013-02-26 00:42:20 +08:00
|
|
|
|
2013-02-06 03:16:51 +08:00
|
|
|
split = @lines[start_row].split("\n")
|
2013-02-26 00:42:20 +08:00
|
|
|
|
2013-02-06 03:16:51 +08:00
|
|
|
if split.length > 1
|
|
|
|
@lines[start_row] = split[0]
|
|
|
|
i = 1
|
|
|
|
split[1..-2].each do |line|
|
|
|
|
@lines.insert(start_row + i, line)
|
|
|
|
i += 1
|
|
|
|
end
|
2023-02-16 17:40:11 +08:00
|
|
|
@lines.insert(i, "") if @lines.length <= i
|
2013-02-06 03:16:51 +08:00
|
|
|
@lines[i] = split[-1] + @lines[i]
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
def to_s
|
|
|
|
@lines.join("\n")
|
|
|
|
end
|
|
|
|
end
|