I would like to be able to get the current usual mode of vim inside a vim script (and not only inside the statusline). I need this functionality to build a vim script linked with ruby script to be able to change keyboard keys colors depend of vim current mode and motion state. My problem is that vim doesn't know to provide his mode state inside vim script (only inside statusline), or i failed to get it. I think it should have a point there to make vim better by provide a helpful mode() function who can really provide vim current mode (not only in normal mode and not only for statusline).

This way dev's users would be able without pain to build script to recognize current vim mode and then build interactive script. Also, i'm now able to get FocusGained (i'm not Windows user, my OS is archlinux and sometimes FreeBSD) with adding ugly/tricky vimscript and i think this point can also be increase for vim source code to be not only for gvim or Windows users.

Try to imagine you want to create a script for color rgb keyboard keys to show currenty mode and aviable keys to hit depend on mode and motion/other state... how to do that if FocusGained and mode() only works for some very limited situations ?

  • 2
    mode() returns 'n', because you are in Normal. And you switch there yourself in order to execute the script. Simply recall the place where that happened. – Matt Feb 2 '20 at 9:38
  • Sorry Matt, you presume something, but you are wrong. The statusline show insert mode, because i'm in insert mode, and mode() return 'n' instead of 'i'. Look: gist.github.com/jerome-diver/b96efb9600bf613aa59683bb2f5f090f – jerome___ Feb 2 '20 at 21:04
  • From :help mode(): "This is useful in the 'statusline' option or when used with remote_expr(). In most other places it always returns 'c' or 'n'." The usual way to accomplish this is to set 'statusline' to include a call to a function that doesn't produce any output but stores the actual mode somewhere (or possibly executes the external command, though you probably don't want to delay writing the status line waiting for an external command to complete...) – filbranden Feb 3 '20 at 4:16
  • 1
    The code in the status line is called by Vim when it thinks it's appropriate. That makes a HUGE difference. For instance, you can catch autocmd SafeState and/or SafeStateAgain and the mode() will return different values. But if you run your script "synchronously", from mapping or such, you can only do this upon switching into normal (like <CR> to end cmdline and execute it in normal mode). – Matt Feb 3 '20 at 7:58
  • 1
    mode() returns an i just fine in insert mode. (E.g., Ctrl-R =mode()) – muru Feb 3 '20 at 8:21

Your Answer

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

Browse other questions tagged or ask your own question.