I was trying to wrap my head around the code of how mame does its UI Paste function (and also the lua does its emu.keypost()) because the text pasting in the apple2e driver seems to scramble the input.

Grep is pretty useful to scan the whole source tree because I couldn't figure out where things are:

-r is recursive
-i is ignore case

grep -r -i "keypost" src/
src/frontend/mame/luaengine.cpp: * emu.keypost(keys) - post keys to natural keyboard
src/frontend/mame/luaengine.cpp:	emu["keypost"] = [this](const char *keys){ machine().ioport().natkeyboard().post_utf8(keys); };
src/frontend/mame/mame.cpp:		std::string val = std::string("emu.keypost('").append(cmd).append("')");

grep -r -i "post_utf8" src/
src/emu/natkeyboard.cpp://  post_utf8 - post a UTF-8 encoded string
src/emu/natkeyboard.cpp:void natural_keyboard::post_utf8(const char *text, size_t length, const attotime &rate)
src/emu/natkeyboard.h:	void post_utf8(const char *text, size_t length = 0, const attotime &rate = attotime::zero);
src/frontend/mame/ui/ui.cpp:		machine().ioport().natkeyboard().post_utf8(text);
src/frontend/mame/luaengine.cpp:	emu["keypost"] = [this](const char *keys){ machine().ioport().natkeyboard().post_utf8(keys); };

grep -r -i "paste" src/
src/frontend/mame/ui/ui.h:	bool can_paste();
src/frontend/mame/ui/ui.h:	void paste();
src/frontend/mame/ui/ui.cpp://  can_paste
src/frontend/mame/ui/ui.cpp:bool mame_ui_manager::can_paste()
src/frontend/mame/ui/ui.cpp://  paste - does a paste from the keyboard
src/frontend/mame/ui/ui.cpp:void mame_ui_manager::paste()
src/frontend/mame/ui/ui.cpp:		// paste command
src/frontend/mame/ui/ui.cpp:		if (machine().ui_input().pressed(IPT_UI_PASTE))
src/frontend/mame/ui/ui.cpp:			paste();

and the actual paste code in ui.cpp:

//  paste - does a paste from the keyboard

void mame_ui_manager::paste()
	// retrieve the clipboard text
	char *text = osd_get_clipboard_text();

	// was a result returned?
	if (text != nullptr)
		// post the text

		// free the string

So it uses the natural keyboard mapping, and what's interesting is if I launch mame with the -natural option, I lose a lot of keyboard functionality.

./mame64 apple2e -natural

Ctrl+C, Ctrl+F doesn't work, left and right arrow don't work, ESC key doesn't work, and the @ disappear and various symbols are shifted.

Also it seems that the keyboard has gotten a lot slower in the "natural mode", there's a bunch of latency and it can't keep up with fast typing.