How can I change the scroll wheel behavior in vim, so that it scrolls instead of moving the cursor?

I would like scrolling up to be equivalent to c-y c-y c-y, and scrolling down to be equivalent to c-e c-e c-e. The documentation here seems to suggest that this should already be the case, or I can work around it by putting this in my .vimrc:

map <ScrollWheelUp> <C-Y>
map <S-ScrollWheelUp> <C-U>
map <ScrollWheelDown> <C-E>
map <S-ScrollWheelDown> <C-D>

Neither of these solutions seem to work. I am using vim from the terminal in Ubuntu 11.10.


Solution 1:

Sorry you had to struggle with this one. It's actually very simple. Just add the following line to your ~/.vimrc:

set mouse=a

With this turned on, you won't be able (in *nix) to copy stuff out of vim by simply selecting it with the mouse; but if you hold down Shift (Option for OSX) while selecting, it'll work as before.

Solution 2:

From my ~/.gvimrc:

"           Scroll Wheel = Up/Down 4 lines
"   Shift + Scroll Wheel = Up/Down 1 page
" Control + Scroll Wheel = Up/Down 1/2 page
"    Meta + Scroll Wheel = Up/Down 1 line
 noremap <ScrollWheelUp>     4<C-Y>
 noremap <ScrollWheelDown>   4<C-E>
 noremap <S-ScrollWheelUp>   <C-B>
 noremap <S-ScrollWheelDown> <C-F>
 noremap <C-ScrollWheelUp>   <C-U>
 noremap <C-ScrollWheelDown> <C-D>
 noremap <M-ScrollWheelUp>   <C-Y>
 noremap <M-ScrollWheelDown> <C-E>
inoremap <ScrollWheelUp>     <C-O>4<C-Y>
inoremap <ScrollWheelDown>   <C-O>4<C-E>
inoremap <S-ScrollWheelUp>   <C-O><C-B>
inoremap <S-ScrollWheelDown> <C-O><C-F>
inoremap <C-ScrollWheelUp>   <C-O><C-U>
inoremap <C-ScrollWheelDown> <C-O><C-D>
inoremap <M-ScrollWheelUp>   <C-O><C-Y>
inoremap <M-ScrollWheelDown> <C-O><C-E>

This has the unfortunate side effect of making it so the scroll wheel doesn't scroll the window under the mouse cursor, but rather the currently active window.

As for whether Vim in a terminal will be able to scroll with the mouse, it depends on if your terminal emulator will pass escape sequences to Vim when the scroll wheel is used. Xterm can do it, although it may require a little help on your part—see ":help xterm-mouse-wheel".