#include <cstdio>
#include <cctype>
#include <cstring>
#include <string>

#define MIN(A,B) \
  ( (B) < (A) ? (B) : (A) )
#define MAX(A,B) \
  ( (B) > (A) ? (B) : (A) )

using namespace std;

/** Application main entry point. */
int
main (
  int     argc,
  char  * argv[ ]
  )
{
  char buf[ 256 ];
  int n;

  fgets ( buf, sizeof ( buf ), stdin );
  sscanf ( buf, "%d", &n );
  while ( n-- )
  {
    string res;
    int m;
    int p = 0;

    fgets ( buf, sizeof ( buf ), stdin );
    *( strchr ( buf, '\n' ) ) = '\0';
    res.assign ( buf );

    fgets ( buf, sizeof ( buf ), stdin );
    sscanf ( buf, "%d", &m );

    while ( m-- )
    {
      fgets ( buf, sizeof ( buf ), stdin );

      if ( !strncmp ( buf, "forward char", 12 ) )
      {
        ++p;
        p = MIN( p, res.size ( ) );
        continue ;
      }
      if ( !strncmp ( buf, "backward char", 13 ) )
      {
        --p;
        p = MAX( p, 0 );
        continue ;
      }
      if ( !strncmp ( buf, "forward word", 12 ) )
      {
        while ( p < res.size ( ) && isspace ( res[ p ] ) ) ++p;
        while ( p < res.size ( ) && !isspace ( res[ p ] ) ) ++p;
        continue ;
      }
      if ( !strncmp ( buf, "backward word", 13 ) )
      {
        while ( p > 0 && isspace ( res[ p - 1 ] ) ) --p;
        while ( p > 0 && !isspace ( res[ p - 1 ] ) ) --p;
        continue ;
      }
      if ( !strncmp ( buf, "insert", 6 ) )
      {
        *( strrchr ( buf, '\"' ) ) = '\0';
        res.insert ( p, strchr ( buf, '\"' ) + 1 );
        p += strlen ( strchr ( buf, '\"' ) + 1 );

        continue ;
      }
      if ( !strncmp ( buf, "delete char", 11 ) )
      {
        if ( p < res.size ( ) ) res.erase ( p, 1 );

        continue ;
      }
      if ( !strncmp ( buf, "delete word", 11 ) )
      {
        int q = p;

        while ( q < res.size ( ) && isspace ( res[ q ] ) ) ++q;
        while ( q < res.size ( ) && !isspace ( res[ q ] ) ) ++q;
        res.erase ( p, q - p );

        continue ;
      }
    }

    printf ( "%s^%s\n"
           , res.substr ( 0, p ).c_str ( )
           , res.substr ( p, res.size ( ) - p ).c_str ( ) );
  }

  return ( 0 );
}