Combining move and scroll
From Vim Tips Wiki
Tip 105 • Previous Tip • Next Tip
Created: September 3, 2001 Complexity: basic Author: Andrew Pimlott Minimum version: 5.7 Karma: 4/5 Imported from: Tip#105
I sometimes found myself moving down a few lines with j, then scrolling down about the same number of lines with <C-E> to put the cursor in roughly the same place as it started. I decided I wanted to map <C-J> (and <C-K>, respectively) to the move-and-scroll operation. First, I did
:map <C-J> <C-E>j
This was pretty good, but behaved funny at the beginning and end of files. Then, I realized that <C-D> already combined move and scroll, so I figured that giving <C-D> a count of 1 would do it:
:map <C-J> 1<C-D>
Unfortunately, this permanently attaches a count to <C-D> (ugh!), so I have to undo that:
:map <C-J> 1<C-D>:set scroll=0<CR>
This has the drawback of not necessarily resetting scroll to its original value, but since I never change scroll, it's good enough for me. It would be nice if there were a version of <C-D> that did not have the side-affect of changing scroll.
[edit] Comments
And for Page-Up/Page-Down, see VimTip320. My solution:
map <PageDown> :set scroll=0<CR>:set scroll^=2<CR>:set scroll-=1<CR><C-D>:set scroll=0<CR> map <PageUp> :set scroll=0<CR>:set scroll^=2<CR>:set scroll-=1<CR><C-U>:set scroll=0<CR>
If you set the scroll to 1 for C-D and C-U, you can still use C-F and C-B to go forward and back one screen per press. Best of both worlds!!
TODO: Merge following into the above tip 105.
Following is from tip 417 that has been removed.
A long time ago, I entered tip 105. I used that mapping for a long time, but it always had a couple problems. One, it reset the scroll parameter. Two, it didn't work in visual mode, because :set scroll exits visual mode. I was reviewing my Vim configuration and learning some new tricks, and in the process I improved this mapping.
Now, Ctrl-J and Ctrl-K will move the cursor one line down or up, and scroll one line down or up--so the cursor remains on the same screen line (except near the beginning and end of the file)--in both normal and visual modes. And the scroll parameter is unaffected.
" N<C-D> and N<C-U> idiotically change the scroll setting
function! s:Saving_scroll(cmd)
let save_scroll = &scroll
execute "normal" a:cmd
let &scroll = save_scroll
endfunction
" move and scroll
nmap <C-J> :call <SID>Saving_scroll("1<C-V><C-D>")<CR>
vmap <C-J> <Esc>:call <SID>Saving_scroll("gv1<C-V><C-D>")<CR>
nmap <C-K> :call <SID>Saving_scroll("1<C-V><C-U>")<CR>
vmap <C-K> <Esc>:call <SID>Saving_scroll("gv1<C-V><C-U>")<CR>
This is an example of several terrible Vim hacks, to boot.
I set 'scrolloff' value for somewhat of the same effect. Your way is more complete though.
