X = 1
Y = 0

class Editor
  def initialize
    @text = []
    @buffer = ''
    @cursor = [0, 0]
  end

  def line_start?
    @cursor[Y] == 0
  end

  def line_end?
    @cursor[Y] == @text.size - 1
  end

  def str_start?
    @cursor[X] == 0
  end

  def str_end?
    y = @cursor[Y]
    @cursor[X] == @text[y].size
  end

  def character?
    (not str_end?)
  end

  attr_accessor :text, :buffer, :cursor
end

class CommandA
  def self.execute editor
    editor.cursor[X] = 0
  end
end

class CommandE
  def self.execute editor
    y = editor.cursor[Y]
    editor.cursor[X] = editor.text[y].size
  end
end

class CommandP
  def self.execute editor
    editor.cursor[Y] -= 1 unless editor.line_start?
    editor.cursor[X] = 0
  end
end

class CommandN
  def self.execute editor
    editor.cursor[Y] += 1 unless editor.line_end?
    editor.cursor[X] = 0
  end
end

class CommandF
  def self.execute editor
    y = editor.cursor[Y]
    if not editor.str_end?
      editor.cursor[X] += 1
    elsif not editor.line_end?
      editor.cursor[Y] += 1
      editor.cursor[X] = 0
    end
  end
end

class CommandB
  def self.execute editor
    if not editor.str_start?
      editor.cursor[X] -= 1
    elsif not editor.line_start?
      editor.cursor[Y] -= 1
      y = editor.cursor[Y]
      editor.cursor[X] = editor.text[y].size
    end
  end
end

class CommandD
  def self.execute editor
    x = editor.cursor[X]
    y = editor.cursor[Y]

    if editor.character?
      editor.text[y].slice!(x)
    elsif editor.str_end? and not editor.line_end?
      editor.text[y] << editor.text[y+1]
      editor.text.slice!(y+1)
    end
  end
end

class CommandK
  def self.execute editor
    x = editor.cursor[X]
    y = editor.cursor[Y]

    if editor.character?
      editor.buffer = editor.text[y].slice!(x..-1)
    elsif editor.str_end? and not editor.line_end?
      editor.buffer = '\n'
      editor.text[y] << editor.text[y+1]
      editor.text.slice!(y+1)
    end
  end
end

class CommandY
  def self.execute editor
    unless editor.buffer.empty?
      x = editor.cursor[X]
      y = editor.cursor[Y]

      if editor.buffer == '\n'
        str = editor.text[y].slice!(x..-1)
        editor.text.insert(y+1, str)
        editor.cursor[X] = 0
        editor.cursor[Y] += 1
      else
        editor.text[y].insert(x, editor.buffer)
        editor.cursor[X] += editor.buffer.size
      end
    end
  end
end

def main
  editor = Editor.new
  loop do
    line = gets.chomp
    break if line == 'END_OF_TEXT'
    editor.text << line
  end

  command_list = []
  loop do
    command = gets.chomp
    break if command == '-'
    command_list << command
  end

  command_list.each do |command|
    eval("Command#{command.upcase}").execute(editor)
  end

  editor.text.each {|line| puts line}
end

main