I'd like to call a (vimscript-) function, if I'm pressing the return key. Is it possible to do that in vim? Because currently this doesn't work:

function Test()
    echom "test"

inoremap <CR> call Test()

When you create an Insert-mode mapping (inoremap), the expansion is interpreted as keystrokes in Insert-mode, so your example will actually just enter the call Test() text as a literal.

In order to call a function from that mapping, you need to first exit Insert mode, then use : to enter the :call command and finally use a <CR> to execute it.

You can also use the <C-O> command, which allows you to execute a single Normal-mode command and return to Insert-mode when done.

This will work to call the function when you press <CR> in Insert-mode:

inoremap <CR> <C-O>:call Test()<CR>
  • Nice! I can call my function but the cursor behaves "strange" but do you have an idea, how I can keep the insert-mode-cursor-behaviour? Like the indentation adjusting if I open write a curly bracket and type enter that my cursor gets the bigger indentation and the ending curly bracket goes to the next line.
    – TornaxO7
    Jan 31 '21 at 1:21
  • Not sure exactly what you mean... If it's related to the position of the cursor (particularly if you're at the end of the line), you could try <C-\><C-O> to see if it preserves it. Your question is asking how to call a function from a mapping (which is what I addressed in my answer.) You might want to post a separate question about what you want to accomplish more specifically, as not always calling a function this way is the best way to do it...
    – filbranden
    Jan 31 '21 at 3:34
  • 1
    You're rigth. I'll mark your answer as accepted and I'll create a new questin for that. Thank you again sir for your answer :)
    – TornaxO7
    Jan 31 '21 at 12:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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