lines = []
while line = gets.chomp
    break if line == "END_OF_TEXT"
    lines << line
end

cursor_y, cursor_x = 0, 0
buffer = nil
while true
    line = gets.chomp
    case line
    when "a"
        cursor_x = 0
    when "e"
        cursor_x = lines[cursor_y].length
    when "p"
        cursor_y -= 1 if cursor_y > 0
        cursor_x = 0
    when "n"
        cursor_y += 1 if cursor_y < lines.length - 1
        cursor_x = 0
    when "f"
        if cursor_x < lines[cursor_y].length
            cursor_x += 1
        else
            if cursor_y < lines.length - 1
                cursor_y += 1
                cursor_x = 0
            end
        end
    when "b"
        if cursor_x > 0
            cursor_x -= 1
        else
            if cursor_y > 0
                cursor_y -= 1
                cursor_x = lines[cursor_y].length
            end
        end
    when "d"
        if cursor_x < lines[cursor_y].length
            lines[cursor_y][cursor_x, 1] = ""
        else
            if cursor_y < lines.length - 1
                lines[cursor_y] += lines[cursor_y + 1]
                lines.delete_at(cursor_y + 1)
            end
        end
    when "k"
        if cursor_x < lines[cursor_y].length
            buffer = lines[cursor_y][cursor_x..-1]
            lines[cursor_y] = lines[cursor_y][0...cursor_x]
        else
            if cursor_y < lines.length - 1
                lines[cursor_y] += lines[cursor_y + 1]
                lines.delete_at(cursor_y + 1)
                buffer = ""
            end
        end
    when "y"
        if buffer == ""
            temp = lines[cursor_y][cursor_x..-1]
            lines[cursor_y] = lines[cursor_y][0...cursor_x]
            cursor_y += 1
            cursor_x = 0
            lines[cursor_y, 0] = temp
        elsif !buffer.nil?
            lines[cursor_y][cursor_x, 0] = buffer
            cursor_x += buffer.length
        end
    when "-"
        break
    end
end
lines.each{|line| puts line}

