1

I am trying to create an Emacs like Ctrl-l feature, similar to Vim's H, M and L. For those who don't now, these keys jump to top, middle, and bottom of the window. I already have something but I am missing the "if" part.

function! ToggleHML()
    let l:winheight = winheight('%')
    let l:top = 1
    let l:middle = l:winheight / 2
    let l:bottom = l:winheight
    if ...
endfunction

I think I have to create another variable to keep the state until the next function call, but I don't know how to.

Another thing I ended up thinking, exec a normal command inside the function. Something like:

:exec 'normal! H'

2 Answers 2

3

This should do what you're looking for:

function! ToggleHML()
    if winline() < winheight('%') / 2
      normal M
    elseif winline() < winheight('%')
      normal L
    else
      normal H
    endif
endfunction

I removed the variables, since they aren't really necessary. This will always jump down unless it's already at the bottom, in which case it will jump up.

2
  • Not yet, it never jumps to the top. Apr 1, 2018 at 10:17
  • The problem with winheight('%') only, is that sometimes we have a file smaller than it, so in my soulution, yes I figured it out, I have an if clause to test if the winheight('%') is bigger than line('$'). Apr 2, 2018 at 17:09
0

After some sweat, I figured out one solution, not so easy as I thought. We have to discover if the file is larger or not than winheight('%').

function! ToggleHML()
    set scrolloff=0
    let l:last_win_line = ( line('$') <= winheight('%') ? line('$')  : winheight('%')  )
    if winline() < l:last_win_line / 2
      normal M
    elseif winline() < l:last_win_line
      normal L
    else
      normal H
    endif
endfunction
nnoremap <C-l> :call ToggleHML()<CR>

Reference: http://vim.1045645.n5.nabble.com/Vim-General-f1139531.html were I figured ou how to get the last line number line('$').

1
  • Special thanks to [vi.stackexchange.com/users/2920/djmcmayhem](DJMcMayhem) for his special interest and giving us the winline() and winheight('%') tips. Apr 1, 2018 at 19:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.