#include <iostream> 
#include <sstream> 
#include <iomanip> 
#include <algorithm> 
#include <cmath> 
#include <string> 
#include <vector> 
#include <list> 
#include <queue> 
#include <stack> 
#include <set> 
#include <map> 
#include <bitset> 
#include <numeric> 
#include <climits> 
#include <cfloat> 
using namespace std; 

int main()
{
    int n;
    cin >> n;
    cin.ignore();

    while(--n >= 0){
        string s;
        getline(cin, s);
        int m;
        cin >> m;
        cin.ignore();

        list<char> text(s.begin(), s.end());
        list<char>::iterator it = text.begin();

        while(--m >= 0){
            string ope;
            getline(cin, ope);

            if(ope == "forward char"){
                if(it != text.end())
                    ++ it;
            }else if(ope == "backward char"){
                if(it != text.begin())
                    -- it;
            }else if(ope == "delete char"){
                if(it != text.end())
                    it = text.erase(it);
            }else if(ope == "forward word"){
                while(it != text.end() && (*it) == ' ')
                    ++ it;
                while(it != text.end() && (*it) != ' ')
                    ++ it;
            }else if(ope == "backward word"){
                if(text.size() > 0 && it != text.begin()){
                    -- it;
                    while(it != text.begin() && (*it) == ' ')
                        -- it;
                    while(it != text.begin() && (*it) != ' ')
                        -- it;
                    if((*it) == ' ')
                        ++ it;
                }
            }else if(ope == "delete word"){
                list<char>::iterator it2 = it;
                while(it2 != text.end() && (*it2) == ' ')
                    ++ it2;
                if(it2 != text.end()){
                    it = text.erase(it, it2);
                    while(it != text.end() && (*it) != ' ')
                        it = text.erase(it);
                }
            }else{
                for(unsigned i=8; i<ope.size()-1; ++i){
                    it = text.insert(it, ope[i]);
                    ++ it;
                }
            }
        }

        cout << string(text.begin(), it) << '^' << string(it, text.end()) << endl;
    }
    
    return 0;
}