char t[1002],m[9],o[999];c,n,w;M(d){t[c]=t[c+d];t[c+d]='^';c+=d;}D(){memmove(t+c+1,t+c+2,strlen(t+c+1));}main(l){scanf("%*d");for(;t[1]=0,getchar(),~scanf("%[^\n]",t+1);){t[0]='^';c=0;scanf("%d",&n);for(;n--;){scanf("%s",m);if(strcmp(m,"insert")==0){scanf(" \"%[^\"]\"",o);l=strlen(o);memmove(t+c+l,t+c,strlen(t+c)+1);memcpy(t+c,o,l);c+=l;}else{scanf("%s",o);w=*o-'c';if(strcmp(m,"forward")==0){if(w){for(;t[c+1]==' ';)M(1);for(;t[c+1]&&t[c+1]!=' ';)M(1);}else{if(t[c+1])M(1);}}else if(strcmp(m,"backward")==0){if(w){for(;c>0&&t[c-1]==' ';)M(-1);for(;c>0&&t[c-1]!=' ';)M(-1);}else{if(c>0)M(-1);}}else{if(w){int p=c;for(;t[p+1]==' ';)p++;if(t[p+1]&&t[p+1]!=' '){for(;t[p+1]&&t[p+1]!=' ';)p++;for(;t[c+1]==' ';)D();for(;t[c+1]&&t[c+1]!=' ';)D();}}else{if(t[c+1])D();}}}}puts(t);}}