#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX 1010
char buffer[MAX], temp[MAX];
int cursor, length;
void print(const char* arg)
{
#ifdef __HOGEOVER30__DEBUG__
	int i;
	printf("%s: ", arg);
	for (i = 0; i < cursor; ++i) putchar(buffer[i]);
	putchar('^');
	for (i = cursor; i < length; ++i) putchar(buffer[i]);
	puts("");
#endif
}
void forwardChar(void)
{
	if (cursor < length) cursor++;
	print("foward char");
}
void forwardWord(void)
{
	if (cursor == length) return;
	while (cursor < length && buffer[cursor] == ' ') cursor++;
	while (cursor < length && buffer[cursor] != ' ') cursor++;
	print("forward word");
}
void backwardChar(void)
{
	if (cursor > 0) cursor--;
	print("backward char");
}
void backwardWord(void)
{
	if (cursor == 0) return;
	while (cursor > 0 && buffer[cursor] == ' ') cursor--;
	while (cursor > 0 && buffer[cursor] != ' ') cursor--;
	print("backward word");
}
void insert(const char* text)
{
	int i;
	int n = strlen(text);
	for (i = length; i >= cursor; --i) buffer[i+n] = buffer[i];
	for (i = 0; i < n; ++i) buffer[cursor++] = text[i];
	while (cursor > 0 && buffer[cursor-1] == ' ') cursor--;
	length += n;
	print("insert");
}
void deleteChar(void)
{
	int i;
	if (cursor == length) return;
	for (i = cursor; i < length; ++i) buffer[i] = buffer[i+1];
	length--;
	print("delete char");
}
void deleteWord(void)
{
	int i;
	int k = 0;
	if (cursor == length) return;
	while (k + cursor < length && buffer[k + cursor] == ' ') k++;
	while (k + cursor < length && buffer[k + cursor] != ' ') k++;
	for (i = cursor; i < length; ++i) buffer[i] = buffer[i+k];
	length -= k;
	print("delete word");
}
int main(void)
{
	int T = atoi(fgets(temp, MAX, stdin));
	while (T--) {
		int i, n;
		fgets(buffer, MAX, stdin);
		buffer[strlen(buffer)-1] = '\0';
		length = strlen(buffer);
		cursor = 0;
		n = atoi(fgets(temp, MAX, stdin));
		for (i = 0; i < n; ++i) {
			fgets(temp, MAX, stdin);
			if (!strcmp(temp, "forward char\n")) forwardChar();
			if (!strcmp(temp, "forward word\n")) forwardWord();
			if (!strcmp(temp, "backward char\n")) backwardChar();
			if (!strcmp(temp, "backward word\n")) backwardWord();
			if (!strcmp(temp, "delete char\n")) deleteChar();
			if (!strcmp(temp, "delete word\n")) deleteWord();
			if (!strncmp(temp, "insert", 6)) {
				strtok(temp, "\"");
				insert(strtok(NULL, "\""));
			}
		}
		for (i = 0; i < cursor; ++i) putchar(buffer[i]);
		putchar('^');
		for (i = cursor; i < length; ++i) putchar(buffer[i]);
		puts("");
	}
	return 0;
}