@buffer = ""
def swap(i, j)
  @buffer[i], @buffer[j] = @buffer[j], @buffer[i]
end
def cursor
  @buffer.index("^")
end

def forwardChar
  swap(cursor, cursor+1) unless cursor == @buffer.size-1
end
def forwardWord
  while cursor < @buffer.size-1 && @buffer[cursor+1] == " " do
    swap(cursor, cursor+1)
  end
  while cursor < @buffer.size-1 && @buffer[cursor+1] != " "
    swap(cursor, cursor+1)
  end
end
def backwardChar
  swap(cursor, cursor-1) unless cursor == 0
end
def backwardWord
  while cursor > 0 && @buffer[cursor-1] == " " do
    swap(cursor, cursor-1)
  end
  while cursor > 0 && @buffer[cursor-1] != " "
    swap(cursor, cursor-1)
  end
end
def insert(text)
  @buffer.insert(cursor, text)
end
def deleteChar
  @buffer.slice!(cursor+1) if @buffer[cursor+1]
end
def deleteWord
  return if @buffer[cursor+1, @buffer.size-cursor-1] !~ /[^ ]/
  while cursor < @buffer.size-1 && @buffer[cursor+1] == " " do
    @buffer.slice!(cursor+1)
  end
  while cursor < @buffer.size-1 && @buffer[cursor+1] != " " do
    @buffer.slice!(cursor+1)
  end
end

gets.to_i.times do
  @buffer = "^"+gets.chomp
  gets.to_i.times do
    case gets.chomp
      when "forward char"
        forwardChar
      when "forward word"
        forwardWord
      when "backward char"
        backwardChar
      when "backward word"
        backwardWord
      when "delete char"
        deleteChar
      when "delete word"
        deleteWord
      when /insert "(.*)"/
        insert($1)
    end
  end
  puts @buffer
end