#include <cstdio>
#include <string>
#include <iostream>

using namespace std;

int n,m;

int main(void){
	scanf("%d%*c",&n);
	for(int dd=0;dd<n;dd++){
		string str;
		getline(cin,str);
		scanf("%d%*c",&m);
		int point=0;
		for(int i=0;i<m;i++){
			string com;
			getline(cin,com);
			if(com=="forward char"){
				if(point<str.size()){
					point++;
				}
			}
			if(com=="forward word"){
				if(point<str.size()){
					while(point<str.size() && str[point]==' ')point++;
					while(point<str.size() && str[point]!=' ')point++;
				}
			}
			if(com=="backward char"){
				if(point>0){
					point--;
				}
			}
			if(com=="backward word"){
				if(point>0){
					while(point>0 && str[point-1]==' ')point--;
					while(point>0 && str[point-1]!=' ')point--;
				}
			}
			if(com[0]=='i'){
				string str2;
				string str3;
				string str4;
				str2=str.substr(0,point);
				str3=str.substr(point);
				str4=com.substr(8,com.size()-9);
				str=str2+str4+str3;
				point+=com.size()-9;
			}
			if(com=="delete char"){
				if(str.size()==point)continue;
				string str2;
				string str3;
				str2=str.substr(0,point);
				str3=str.substr(point+1);
				str=str2+str3;
			}
			if(com=="delete word"){
				if(str.size()==point)continue;
				int e=1;
				if(str[point]==' '){
					while(point+e<str.size() && str[point+e]==' ')e++;
				}
				int flag2=0;
				while(point+e<str.size() && str[point+e]!=' '){
					e++;
					flag2=1;
				}
				if(flag2==0)continue;
				string str2;
				string str3;
				str2=str.substr(0,point);
				str3=str.substr(point+e);
				str=str2+str3;
			}
			//cout << str << endl;
		}
		string res="";
		for(int i=0;i<str.size();i++){
			if(i==point)res+='^';
			res+=str[i];
		}
		if(str.size()==point)res+='^';
		cout << res << endl;
	}
	return 0;
}