I don't have a Mac handy to test this answer, but I encounter this problem in XTerm under Linux very occasionally and (assuming iTerm2 respects the same control codes) you might find the fix below helpful.
Run the following shell command inside the terminal where you're seeing the problem:
(Note that the last character there is a lower-case 'ell'.)
This ANSI control sequence is like the one listed in Thomas Dickey's answer, but it turns the feature off (rather than on). It should solve your problem in all applications, not just Vim, by stopping the characters from occurring at all.
On Linux I can demonstrate this control sequence working with the following steps:
xterm and enable the feature by running
printf "\e[?1004h" in it.
xeyes or some other GUI application from that same XTerm. (For some reason, this effect does not happen for me until the XTerm in question launches an application. Anybody know why?)
- Repeatedly switch focus into and out of the original XTerm (e.g. by clicking on windows) and see
^[[I being "typed" into the original XTerm.
- Now close Xeyes, return to the original XTerm, and run
printf "\e[?1004l" (to disable the feature, as described in the fix above).
- Repeat the "run
xeyes, switch focus" steps above, but this time see no characters being entered in the terminal.
I personally only see this problem if I've inadvertently dumped binary output to the terminal, but if you're encountering it more regularly you might want to add that
printf to your shell's interactive startup script (e.g.
~/.bashrc). There doesn't appear to be any harm (under XTerm at least) to sending the control code if the feature is already disabled, so it should be safe even if you only see this problem sometimes.
If you're concerned about your shell always generating that output, perhaps because you sometimes use it in places that don't handle those control codes well, or if the problem is sometimes triggered after the shell starts up, then you might prefer to set up an alias (e.g. with
alias focusfix='printf "\e[?1004l"') to make it more convenient to run manually.