Weird insertion from Vim on mouse click

I'm using putty (on windows 7) to connect to shell and Vim as editor. I also have mouse=a option enabled in Vim, but I get some strange behavior (such as random insertions of characters and/or linebreaks) when I click to the right side of the Vim window (let's say it's like 70%+ of the screen width area where it gets weird). I'm slowly getting used to such behavior, but I'd really like to know if I could somehow fix this.


Solution 1:

PuTTY sends mouse events using an xterm protocol that dates back all the way to X10 in the mid-eighties. This encodes the mouse coordinates with a single byte each for row and column, whereby 32 (the ASCII code for a space character) is added. This allows for coordinates up to 223 (which is 255 - 32).

Unfortunately that encoding does not adhere to the applicable standards for terminal control sequences, and the range can effectively be further restricted to 95 (i.e. 127 - 32) if applications don't make special allowances for it. In particular, if an application performs UTF-8 decoding before control sequence parsing, mouse coordinates beyond 95 just end up being treated as invalid UTF-8.

During the past year, several attempts have been made to address this issue in xterm. The best one of those is the so-called SGR 1006 mode added in patch #277, which uses a standard-compliant control sequence with unlimited coordinates. Support for this will slowly permeate to other terminal emulators and applications.

Solution 2:

This has been fixed in Vim 7.3.632. See :h sgr-mouse. Or just put this in your ~/.vimrc:

set ttymouse=sgr

If you want to be compatible with versions that don't have mouse_sgr compiled in, use:

if has("mouse_sgr")
    set ttymouse=sgr
else
    set ttymouse=xterm2
end

To see if your version of Vim has mouse_sgr, run vim --version from the command-line, or in Vim, enter :version, and look for +mouse_sgr.