def last_word?(cur)
  @lines[cur[0]].size == cur[1]
end

def last_line?(cur)
  cur[0] == @lines.size - 1
end

buf = ''
cur = [0, 0]
@lines = []
while l = gets.chomp
  break if l == 'END_OF_TEXT'
  @lines << l
end

while cmd = gets.chomp
  break if cmd == '-'
  case cmd
  when 'a'
    cur[1] = 0
  when 'e'
    cur[1] = @lines[cur[0]].size
  when 'p'
    cur[0] == 0 ? cur[1] = 0 : cur = [cur[0] - 1, 0]
  when 'n'
    last_line?(cur) ? cur[1] = 0 : cur = [cur[0] + 1, 0]
  when 'f'
    unless last_word?(cur)
      cur[1] += 1
    else
      unless last_line?(cur)
        cur = [cur[0] + 1, 0]
      end
    end
  when 'b'
    if cur[1] != 0
      cur[1] -= 1
    else
      if cur[0] != 0
        cur = [cur[0] - 1, @lines[cur[0] - 1].size]
      end
    end
  when 'd'
    if last_word?(cur) && !last_line?(cur)
      l = @lines.delete_at(cur[0] + 1)
      @lines[cur[0]] += l
    elsif !last_word?(cur)
      @lines[cur[0]].slice!(cur[1])
    end
  when 'k'
    if last_word?(cur) && !last_line?(cur)
      l = @lines.delete_at(cur[0] + 1)
      @lines[cur[0]] += l
      buf = "\\n"
    elsif !last_word?(cur)
      buf = @lines[cur[0]].slice!(cur[1]..-1)
    end
  when 'y'
    if buf == "\\n"
      @lines.insert(cur[0] + 1, @lines[cur[0]].slice!(cur[1]..-1))
      cur = [cur[0] + 1, 0]
    elsif buf != ''
      @lines[cur[0]].insert(cur[1], buf)
      cur[1] += buf.size
    end
  end
end

puts @lines