sponsor Vim development Vim logo Vim Book Ad

intermediate Tip #417: combining move and scroll [IMPROVED]

 tip karma   Rating 24/9, Viewed by 1231 

created:   February 3, 2003 14:29      complexity:   intermediate
author:   Andrew Pimlott      as of Vim:   5.7

A long time ago, I entered vimtip #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

    " 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.

 rate this tip  Life Changing Helpful Unfulfilling 

<<Fix error "E97: Cannot create diffs" on VIM for Windows | Stop the beeping in gvim. >>

Additional Notes

bach2tony@yahoo.com, February 6, 2003 9:48
vimizer, February 8, 2003 19:21
I set 'scrolloff' value for somewhat of the same effect.  Your way is more complete though.
mkelly@hp.com, February 10, 2003 21:34

Thanks, this is great, almost exaclty what I was looking for !
The only two things left I still am searching for are :

1) (related) I want to keep the cursor column in the same place -
     unless the new line is shorter in which case go to the end of
     the new line.  This always puts the column at 0 when I scroll.
     Still excellent tho, thanks !

2). (not related) I want to restore the screen buffer to what it was
      before I entered vim.  I think a ioctl/tcgetattr to get the initial
      settings and then another one at the end to restore might
      do it - but I am just looking at the code now to see how/where.
      Maybe there is a better way ?

thanks for your help,
If you have questions or remarks about this site, visit the vimonline development pages. Please use this site responsibly.
Questions about Vim should go to vim@vim.org after searching the archive. Help Bram help Uganda.
Sponsored by Web Concept Group Inc. SourceForge Logo