Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detecting the mode inside a function called from a plain :map

Tags:

vim

Is it possible to :map to a function that can detect the mode it was called in? This is what I have:

func! s:ShowModeFunction()
    echomsg mode(1)
endfunc

noremap <expr> <Plug>ShowMode <SID>ShowModeFunction()

map \m <Plug>ShowMode

The map \m eventually calls the top function, which echos a string indicating normal mode, operator-pending mode, or any of the Visual modes.

This only works with <expr> on the middle map though; any colon command would render the final mode() call useless, because it would then always return "normal mode". Unfortunately, <expr> strictly requires an expression on the right-hand side, and since the function doesn't return anything, the implicit return value 0 is used, which moves the cursor to the first column.

like image 870
glts Avatar asked Dec 14 '25 17:12

glts


1 Answers

Just make the function return nothing, this is then a no-op in the expression mapping:

func! s:ShowModeFunction()
    echomsg mode(1)
    return ''
endfunc

If there's any other limitation in map-expr, just set a variable in there, and do the real work (including evaluating the variable) in a "normal" mapping or :call that you can append to your <Plug>ShowMode mapping (or another intermediate one, to keep the customizability).

like image 197
Ingo Karkat Avatar answered Dec 18 '25 02:12

Ingo Karkat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!