#include "bits/stdc++.h"
#include<unordered_map>
#include<unordered_set>
#pragma warning(disable:4996)
using namespace std;
using ld = long double;
const ld eps = 1e-9;

//// < "d:\d_download\visual studio 2015\projects\programing_contest_c++\debug\a.txt" > "d:\d_download\visual studio 2015\projects\programing_contest_c++\debug\b.txt"

void pr(string st, int i) {
	for (int c = 0; c < st.size(); ++c) {
		if (c == i)cout << '^';
		cout << st[c];
	}
	if (i == st.size())cout << '^';
	cout << endl;
}

int main() {
	int N; cin >> N;
	string dummy;
	getline(cin, dummy);
	while (N--) {
		string st;
		getline(cin, st);
		int M; cin >> M;
		int i = 0;
		getline(cin, dummy);
		while (M--) {
			string order; getline(cin, order);
			if (order == "forward char") {
				if (i != st.size())i++;
			}
			else if (order == "forward word") {
				while (i != st.size() && st[i] == ' ') {
					i++;
				}
				while (i != st.size()&&st[i]!=' ') {
					i++;
				}
			}
			else if (order == "backward char") {
				if (i)i--;
			}
			else if (order == "backward word") {
				while (i && st[i - 1] == ' ') {
					i--;
				}
				while (i && st[i-1] != ' ') {
					i--;
				}
			}
			else if (order == "delete char") {
				if (i != st.size()) {
					st.erase(i,1);
				}
			}
			else if (order == "delete word") {
				if (st.find_first_not_of(' ',i) != string::npos) {
					while (i != st.size() && st[i] == ' ') {
						st.erase(i, 1);
					}
					while (i != st.size() && st[i] != ' ') {
						st.erase(i, 1);
					}
				}
				
			}
			else {
				string ins = order.substr(order.find(' ') + 2, order.size()-3- order.find(' '));
				st.insert(i, ins);
				i += ins.size();
			}

			//pr(st, i);
		}
		pr(st, i);
	}
	return 0;
}