vim - Run ex command to go to line from function in normal mode

212 Views Asked by At

I have a function setup to run on InsertEnter autocmd. In the function I want to jump to a specific line.

So what I have tried (simplified) is this so far:

function JumpToLineBeforeScroll()
    echom "function runs"
    exe ":10"
    return ""
endfunction

autocmd InsertEnter * call JumpToLineBeforeScroll() | set cul

I verified using mode() that while this function runs it is in normal mode (pls correct me if wrong). Function runs but the line jump is not working. How do I get this to work ?

Note: What I am actually trying to achieve is on mouse scroll while in insert mode, switch to normal mode, save the current line number and then scroll. Then once I press i to enter insert mode again (InsertEnter) I want to jump back to the last line I was on before scroll. As this would need some conditionals I want to keep this in a function instead of writing the entire code in the autocmd line itself.

Thanks!

1

There are 1 best solutions below

0
Devansh Sharma On BEST ANSWER

So gi exists :)

Now after learning about gi and realising how :normal works, I've reached this config which works for my usecase perfectly. And turns out autocmd is not actually needed for this as :startinsert also exists :)

" Variable to track scrolling
let didScroll = 0

" Function to track if scrolling happened
function ScrollHandler()
    let g:didScroll = 1
    return ""
endfunction

" Function to jump back to line before scrolling started
function JumpToLineBeforeScroll()
    if g:didScroll > 0
        let g:didScroll = 0
        :normal gi
    endif
    " Needed as :normal ends with an <Esc> and so comes back to ex mode
    startinsert
    return ""
endfunction

" Map mouse scroll wheel to only scroll the screen
nnoremap <ScrollWheelUp> <Esc>:call ScrollHandler()<CR><C-y>
nnoremap <ScrollWheelDown> <Esc>:call ScrollHandler()<CR><C-e>
inoremap <ScrollWheelUp> <Esc>:call ScrollHandler()<CR><C-y>
inoremap <ScrollWheelDown> <Esc>:call ScrollHandler()<CR><C-e>
" Normal mode mapping for i which performs gi to jump to last insertmode line if scroll has taken place
nnoremap i <Esc>:call JumpToLineBeforeScroll()<CR>

I'm still using didScroll since I dont always want to do a gi whenever I press i. If that's the setup any navigation in normal mode would be pointless as I would be back to same line when enter back insert.