#include <stdio.h>
#include <stdlib.h>
#include <string.h>

static
char cln[ 256 ];

void getNextLine (
  void
  )
{
  fgets ( cln, sizeof ( cln ), stdin );
  *( strchr ( cln, '\n' ) ) = '\0';
}

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

  getNextLine ( );
  tc = atoi ( cln );

  while ( tc-- )
  {
    char    s[ 1024 ];
    char  * c
       ,  * e
       ,  * p;
    int n;

    getNextLine ( );
    memcpy ( s, cln, sizeof ( cln ) );
    c = s; e = s + strlen ( s );

    getNextLine ( );
    n = atoi ( cln );

    while ( n-- )
    {
      getNextLine ( );

      if ( !strcmp ( cln, "forward char" ) )
      {
        c += !!( c != e );
      }
      else if ( !strcmp ( cln, "forward word" ) )
      {
        while ( c != e && *c == ' ' ) ++c;
        while ( c != e && *c != ' ' ) ++c;
      }
      else if ( !strcmp ( cln, "backward char" ) )
      {
        c -= !!( c != s );
      }
      else if ( !strcmp ( cln, "backward word" ) )
      {
        while ( c != s && c[ -1 ] == ' ' ) --c;
        while ( c != s && c[ -1 ] != ' ' ) --c;
      }
      else if ( !strcmp ( cln, "delete char" ) )
      {
        for ( p = c; p != e && p + 1 != e; ++p ) p[ 0 ] = p[ 1 ];
        e -= !!( c != e );
      }
      else if ( !strcmp ( cln, "delete word" ) )
      {
        size_t len;

        p = c;
        while ( p != e && *p == ' ' ) ++p;
        while ( p != e && *p != ' ' ) ++p;
        len = p - c;

        for ( p = c; p != e && p + len != e; ++p ) p[ 0 ] = p[ len ];
        e -= len;
      }
      else /* insert */
      {
        size_t len;

        for ( p = cln + 8; *p != '\"'; ++p );
        len = p - ( cln + 8 );

        e += len;
        for ( p = e; p - len != c; --p )  p[ -1 ] = p[ -( len + 1 ) ];

        for ( p = c; p != c + len; ++p )  *p = cln[ 8 + ( p - c ) ];
        c += len;
      }
    }

    for ( p = s; ( p - 1 ) != e; ++p )
    {
      if ( p == c ) putchar ( '^' );
      if ( p != e ) putchar ( *p );
    }
    puts ( "" );
  }

  return ( 0 );
}