#include <string>
#include <iostream>
#include <algorithm>
using namespace std;

class text_editor {
private:
	string text;
public:

	void read_text(istream &in) {
		string line;
		getline(in,line);
		this->text = "^" + line;
	}

	void forward_char() {
		auto cursor = find(this->text.begin(),this->text.end(),'^');
		if (cursor + 1 != this->text.end()) { // if cursor not at the end of text
			swap(*cursor,*(cursor + 1));
		}
	}

	void forward_word() {
		auto cursor = find(this->text.begin(),this->text.end(),'^');
		while (cursor + 1 != this->text.end() && *(cursor + 1) == ' ') {
			swap(*cursor,*(cursor + 1));
			++cursor;
		}
		while (cursor + 1 != this->text.end() && *(cursor + 1) != ' ') {
			swap(*cursor,*(cursor + 1));
			++cursor;
		}
	}

	void backward_char() {
		auto cursor = find(this->text.begin(),this->text.end(),'^');
		if (cursor != this->text.begin()) {
			swap(*cursor,*(cursor - 1));
		}
	}

	void backward_word() {
		auto cursor = find(this->text.begin(),this->text.end(),'^');
		while (cursor != this->text.begin() && *(cursor - 1) == ' ') {
			swap(*cursor,*(cursor - 1));
			--cursor;
		}
		while (cursor != this->text.begin() && *(cursor - 1) != ' ') {
			swap(*cursor,*(cursor - 1));
			--cursor;
		}
	}

	void delete_char() {
		auto cursor = find(this->text.begin(),this->text.end(),'^');
		if (cursor + 1 != this->text.end()) {
			this->text.erase(cursor + 1);
		}
	}

	void delete_word() {
		auto cursor = find(this->text.begin(),this->text.end(),'^');
		auto pos = cursor + 1;
		while (pos != this->text.end() && *pos == ' ') {
			++pos;
		}
		if (pos != this->text.end()) {
			this->text.erase(cursor + 1,find(pos,this->text.end(),' '));
		}
	}

	void insert_any_text(string any_text) {
		this->text.insert(this->text.find('^'),any_text);
	}

	string get_text() {
		return this->text;
	}
};

int main() {
	text_editor edtr;
	int n; // number of texts
	cin >> n;
	cin.ignore();
	while (n--) {
		edtr.read_text(cin);
		int cmd_num; // number of commands
		cin >> cmd_num;
		cin.ignore();
		while (cmd_num--) {
			string cmd;
			getline(cin,cmd);
			if (cmd == "forward char") {
				edtr.forward_char();
			} else if (cmd == "forward word") {
				edtr.forward_word();
			} else if (cmd == "backward char") {
				edtr.backward_char();
			} else if (cmd == "backward word") {
				edtr.backward_word();
			} else if (cmd == "delete char") {
				edtr.delete_char();
			} else if (cmd == "delete word") {
				edtr.delete_word();
			} else { // insert "any-text"
				auto first_quot = cmd.find_first_of("\"");
				auto last_quot = cmd.find_last_of("\"");
				edtr.insert_any_text(cmd.substr(first_quot + 1,last_quot - first_quot - 1));
			}
		}
		cout << edtr.get_text() << endl;
	}
}