### main

n = gets.to_i

n.times do
  text = gets.delete("\r\n")
  #p text

  pos = 0
  tlen = text.length

  nc = gets.to_i

  nc.times do
    cline = gets.strip

    case cline
    when 'forward char'
      pos += 1 if pos < tlen
    when 'forward word'
      pos += 1 while pos < tlen && text[pos] == ' '
      pos += 1 while pos < tlen && text[pos] != ' '
    when 'backward char'
      pos -= 1 if pos > 0
    when 'backward word'
      pos -= 1 while pos > 0 && text[pos - 1] == ' '
      pos -= 1 while pos > 0 && text[pos - 1] != ' '
    when 'delete char'
      if pos < tlen
        text[pos] = ''
        tlen -= 1
      end
    when 'delete word'
      pos0 = pos
      pos0 += 1 while pos0 < tlen && text[pos0] == ' '
      pos1 = pos0
      pos1 += 1 while pos1 < tlen && text[pos1] != ' '
      if pos0 != pos1
        text[pos...pos1] = ''
        tlen -= pos1 - pos
      end
    else
      text0 = cline.split('"').last
      text[pos, 0] = text0
      tlen += text0.length
      pos += text0.length
    end
  end

  text[pos, 0] = '^'
  puts text
end