Scrolling Vim relative to cursor, custom mapping

So I have read :help scroll-cursor and really like zz , which puts the line your cursor is on in the middle of your window.

I'm looking for help to make a mapping that would perform similar to zz but puts the line my cursor is on at 20% of the window height (or 25%, 30% etc).


Edit:

Thanks to ZyX and Drasill, I was able to modify his function to get the desired functionality:

function ScrollToPercent(percent)
    let movelines=winheight(0)*a:percent/100

    if has("float") && type(movelines)==type(0.0)
        let movelines=float2nr(movelines)
    endif

    let oldso=&so
    execute ":set so=" . movelines
    execute "normal! zt"
    execute ":set so=" . oldso
endfunction

function ScrollToPercent(percent)
    let curlnr=line('.')
    let targetlnr=line('w0')+(winheight(0)*a:percent/100)
    let movelines=targetlnr-curlnr
    if movelines<0
        let motion='k'
        let movelines=-movelines
    elseif movelines>0
        let motion='j'
    else
        return 0
    endif
    if has("float") && type(movelines)==type(0.0)
         let movelines=float2nr(movelines)
    endif
    execute "normal! ".movelines.motion
endfunction
Sorry, this function changes the current line, while you need to change the window position of the current line. Here is the right one:

function! ScrollToPercent(percent)
    let movelines=winheight(0)*(50-a:percent)/100
    echo movelines
    if movelines<0
        let motion='k'
        let rmotion='j'
        let movelines=-movelines
    elseif movelines>0
        let motion='j'
        let rmotion='k'
    else
        return 0
    endif
    if has('float') && type(movelines)==type(0.0)
        let movelines=float2nr(movelines)
    endif
    execute 'normal! zz'.movelines.motion.'zz'.movelines.rmotion
endfunction

Put this function in your .vimrc and define a mapping, such as:

nnoremap z%2 :<C-u>call ScrollToPercent(20)<CR>

This is not specifically an answer to your question, but you might like the scrolloff option.

For example: :set scrolloff=5 will always leave 5 visible lines at the start and the end of your window.

So, when you use zt or zb , your cursor will go 5 lines under top (or 5 lines above bottom, respectively), which can almost be your desired 20%.

I personally love this setting.

:help scrolloff

我知道zbzt分别将当前行滚动到底部或顶部?

链接地址: http://www.djcxy.com/p/49514.html

上一篇: vim:autoindent不工作

下一篇: 相对于游标滚动Vim,自定义映射