0

Let's say I have a visual selection:

enter image description here

How would I print the mode from the commandline? I've tried doing:

:'<,'><C-U>echom mode()

And a few variations of that, but haven't been able to figure out how to see that I'm in visual (or visual-line) mode. How would I properly do that?

3
  • 1
    Are you trying to show your mode at the bottom of the screen with showmode or to print the current mode you're in with mode()? – Biggybi Jun 20 '20 at 2:14
  • @Biggybi print the mode -- for me to use in a command (this is to debug it) – David542 Jun 20 '20 at 2:15
  • 1
    Please, read :h mode-switching carefully. – Matt Jun 20 '20 at 8:42
2

It's typically pretty hard to be able to tell the mode from a function or even a mapping, since usually the commands you'd have to execute to retrieve the current mode will switch you to another mode already.

For example, when you do :echo mode() you'll have switched to command-line mode with the :, so it will simply return c rather than the normal or visual mode you were in.

This is mentioned in :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".

For specific situations, such as querying which Visual mode was used last, you can use visualmode(), but that tells you nothing about whether you're coming to the current mode from Visual mode, or how long ago Visual mode was last used...


You might have less interference by using an <expr> mapping, in which case mode() will be evaluated before most mode changes happen.

function! Debug(mode, saymode)
  let cmd = "echom 'Mode is [".strtrans(a:saymode)."]'\r"
  if a:mode ==# 'n'
    return ":".cmd
  elseif a:mode ==# 'i'
    return "\<C-o>:".cmd
  elseif a:mode ==# 'v'
    return ":\<C-u>".cmd."gv"
  endif
endfunction
nnoremap <expr> <F2> Debug('n', mode())
inoremap <expr> <F2> Debug('i', mode())
vnoremap <expr> <F2> Debug('v', mode())

But even in that case, it's not really completely reliable. For example, if you're in "Select" mode, Vim will switch you to the corresponding Visual mode before executing a mapping, so this will show the Visual mode rather than Select mode...

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.