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

int main(void) {
	int text_num,now_text;
	char buffer[2000];
	int command_num,now_command;
	char command[200];
	char* cptr;
	char* hikisuu;
	int cursor;
	int buffer_length;
	int text_length;
	int word_flag;
	int i;
	scanf("%d ",&text_num);
	for(now_text=0;now_text<text_num;now_text++) {
		fgets(buffer,sizeof(buffer),stdin);
		cptr=strchr(buffer,'\n');
		if(cptr)*cptr=0;
		scanf("%d ",&command_num);
		cursor=0;
		buffer_length=strlen(buffer);
		for(now_command=0;now_command<command_num;now_command++) {
			fgets(command,sizeof(command),stdin);
			cptr=strchr(command,'\n');
			if(cptr)*cptr=0;
			hikisuu=strchr(command,' ');
			if(hikisuu) {
				*hikisuu=0;
				hikisuu++;
			} else hikisuu=&command[strlen(command)];

			if(strcmp(command,"forward")==0) {
				if(strcmp(hikisuu,"char")==0) {
					if(cursor<buffer_length)cursor++;
				} else if(strcmp(hikisuu,"word")==0) {
					word_flag=0;
					for(;cursor<buffer_length;cursor++) {
						if(isspace(buffer[cursor])) {
							if(word_flag)break;
						} else {
							word_flag=1;
						}
					}
				} else return 1;
			} else if(strcmp(command,"backward")==0) {
				if(strcmp(hikisuu,"char")==0) {
					if(cursor>0)cursor--;
				} else if(strcmp(hikisuu,"word")==0) {
					word_flag=0;
					for(cursor--;cursor>=0;cursor--) {
						if(isspace(buffer[cursor])) {
							if(word_flag)break;
						} else {
							word_flag=1;
						}
					}
					cursor++;
				} else return 1;
			} else if(strcmp(command,"insert")==0) {
				text_length=strlen(hikisuu)-2;
				if(hikisuu[0]!='\"' || hikisuu[text_length+1]!='\"') {
					return 1;
				}
				memmove(&buffer[cursor+text_length],&buffer[cursor],
					strlen(&buffer[cursor])+1);
				memmove(&buffer[cursor],&hikisuu[1],text_length);
				cursor+=text_length;
				buffer_length=strlen(buffer);
			} else if(strcmp(command,"delete")==0) {
				if(strcmp(hikisuu,"char")==0) {
					memmove(&buffer[cursor],&buffer[cursor+1],
						strlen(&buffer[cursor+1])+1);
				} else if(strcmp(hikisuu,"word")==0) {
					word_flag=0;
					for(i=0;cursor+i<buffer_length;i++) {
						if(isspace(buffer[cursor+i])) {
							if(word_flag)break;
						} else {
							word_flag=1;
						}
					}
					if(word_flag) {
						memmove(&buffer[cursor],&buffer[cursor+i],
							strlen(&buffer[cursor+i])+1);
					}
				} else return 1;
				buffer_length=strlen(buffer);
			} else return 1;
		}
		for(i=0;i<buffer_length;i++) {
			if(cursor==i)putchar('^');
			putchar(buffer[i]);
		}
		if(cursor==buffer_length)putchar('^');
		putchar('\n');
	}
	return 0;
}