// Aizu 1101: A Simple Offline Text Editor
// 2017.9.18 bal4u@uu

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

char buf[1010], *p;

int main()
{
	int n, m, cmd, par, f;
	char t[200], *cp, *q, *qq;

	fgets(t, 50, stdin), n = atoi(t); while (n-- > 0) {
		fgets(buf, 1000, stdin);
		p = buf + strlen(buf) - 1; if (*p < ' ' && p >= buf) *p = 0; p = buf; // remove '\n'
		fgets(t, 50, stdin), m = atoi(t); while (m-- > 0) {
			fgets(t, 150, stdin); cp = t; while (*cp == ' ') cp++;
			cmd = *cp; while (*cp >= 'a') cp++; while (*cp == ' ') cp++;
			par = *cp;
			if (cmd == 'f') {    // forward
				if (!*p) continue;
				if (par == 'c') p++;
				else { while (*p == ' ') p++; while (*p > ' ') p++; }
			} else if (cmd == 'b') {   // backward
				if (p == buf) continue;
				if (par == 'c') p--;
				else {
					f = 1, p--;
					while (f && *p <= ' ') { if (p == buf) f = 0; else p--;	}
					while (f && *p >  ' ') { if (p == buf) f = 0; else p--; }
					if (f && *p == ' ') p++;
				}
			} else if (cmd == 'd') {  // delete
				if (!*p) continue;
				if (par == 'c') {
					qq = p, q = p+1; while (*p) *p++ = *q++; *p = 0; p = qq;
				} else {
					f = 0, q = p; while (*q == ' ') q++; while (*q > ' ') f = 1, q++;
					if (f) { qq = p; while (*p) *p++ = *q++; *p = 0; p = qq; }
				}
			} else {  // insert
				int w = strlen(cp)-2;
				q = cp + w; if (*q == '"') w--;  // remove '\n'
				if (w > 0) {
					q = buf + strlen(buf);
					while (p <= q) *(q + w) = *q, q--;
				}
				cp++; while (w-- > 0) *p++ = *cp++;
			}
//printf("#"); q = buf; while (q < p) putchar(*q++); putchar('^'); while (*q) putchar(*q++); putchar('\n');
		}
		q = buf; while (q < p) putchar(*q++); putchar('^'); while (*p) putchar(*p++); putchar('\n');
	}
	return 0;
}