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

int n,m;
int dd,i,j;
char str[1000],com[1000],res[1000];
char str2[1001],str3[1001],str4[1001];
int main(void){
	scanf("%d%*c",&n);
	for(dd=0;dd<n;dd++){
		memset(str,'\0',sizeof(str));
		fgets(str,999,stdin);
		scanf("%d%*c",&m);
		int len=strlen(str)-1;
		int point=0;
		for(i=0;i<m;i++){
			memset(com,'\0',sizeof(com));
			fgets(com,999,stdin);
			int comlen=strlen(com)-1;
			if(com[0]=='f' && com[8]=='c'){
				if(point<len){
					point++;
				}
			}
			if(com[0]=='f' && com[8]=='w'){
				if(point<len){
					while(point<len && str[point]==' ')point++;
					while(point<len && str[point]!=' ')point++;
				}
			}
			if(com[0]=='b' && com[9]=='c'){
				if(point>0){
					point--;
				}
			}
			if(com[0]=='b' && com[9]=='w'){
				if(point>0){
					while(point>0 && str[point-1]==' ')point--;
					while(point>0 && str[point-1]!=' ')point--;
				}
			}
			if(com[0]=='i'){
				memset(str2,'\0',sizeof(str2));
				memset(str3,'\0',sizeof(str3));
				memset(str4,'\0',sizeof(str4));
				for(j=0;j<point;j++){
					str2[j]=str[j];
				}
				for(j=point;j<len;j++){
					str3[j-point]=str[j];
				}
				for(j=8;j<comlen-1;j++){
					str4[j-8]=com[j];
				}
				memset(str,'\0',sizeof(str));
				for(j=0;j<point;j++){
					str[j]=str2[j];
				}
				for(j=0;j<comlen-9;j++){
					str[j+point]=str4[j];
				}
				for(j=0;j<len-point;j++){
					str[j+point+comlen-9]=str3[j];
				}
				len=len+comlen-9;
				point+=comlen-9;
			}
			if(com[0]=='d' && com[7]=='c'){
				if(len==point)continue;
				memset(str2,'\0',sizeof(str2));
				memset(str3,'\0',sizeof(str3));
				for(j=0;j<point;j++){
					str2[j]=str[j];
				}
				for(j=point+1;j<len;j++){
					str3[j]=str[j];
				}
				memset(str,'\0',sizeof(str));
				for(j=0;j<point;j++){
					str[j]=str2[j];
				}
				for(j=point+1;j<len;j++){
					str[j-1]=str3[j];
				}
				len--;
			}
			if(com[0]=='d' && com[7]=='w'){
				if(len==point)continue;
				int e=1;
				if(str[point]==' '){
					while(point+e<len && str[point+e]==' ')e++;
				}
				int flag2=0;
				while(point+e<len && str[point+e]!=' '){
					e++;
					flag2=1;
				}
				if(flag2==0)continue;
				memset(str2,'\0',sizeof(str2));
				memset(str3,'\0',sizeof(str3));
				for(j=0;j<point;j++){
					str2[j]=str[j];
				}
				for(j=point+e;j<len;j++){
					str3[j-point-e]=str[j];
				}
				memset(str,'\0',sizeof(str));
				for(j=0;j<point;j++){
					str[j]=str2[j];
				}
				for(j=point+e;j<len;j++){
					str[j-e]=str3[j-point-e];
				}
				len=len-e;
			}
		}
		int reslen=0;
		memset(res,'\0',sizeof(res));
		for(i=0;i<len;i++){
			if(i==point)res[reslen++]='^';
			res[reslen++]=str[i];
		}
		if(len==point)res[reslen++]='^';
		printf("%s\n",res);
	}
	return 0;
}