Reputation: 8129
What is the best way to check in a vimscript which visual mode is currently active (visual or visual block)?
I've read about mode()
but I can't make it work.
echo mode()
doesn't work for me
if mode() == "v"
doesn't work for me as well.
Upvotes: 12
Views: 3457
Reputation: 3627
Old question. Came here via DDG search.
The function mode does not work inside a vimscript.
There is a new function visualmode that's meant to be used in vimscript functions. It returns the last used visual mode. So to check for block visual mode...
if visualmode() == "\<C-V>"
" we are in visual block mode
endif
Upvotes: 0
Reputation: 384474
@Remonn already said it in the comments, but it was not very clear to me. This is how I managed to see results:
function! F()
normal! gv
throw mode()
endfunction
vnoremap <F9> <ESC>:call F()<CR>
Go into different visual modes and then hit F9
to see.
I need a throw because the -- VISUAL --
line covers any echo message. Can anyone echo in VISUAL mode?
In general, I think the best thing to do when you would need mode()
is to make two different mappings, and then either two different functions that do completely different things:
function! Fnorm()
endfunction
function! Fvis()
endfunction
nnoremap <F9> :call Fnorm()<CR>
nnoremap <F9> <ESC>:call Fvis()<CR>gv
or one single function and give different parameters to it depending on the mapping:
function! F(param)
endfunction
nnoremap <F9> :call F(1)<CR>
nnoremap <F9> <ESC>:call F(2)<CR>gv
Another related trick is what to do if you want to do something while you are in visual mode, like move the cursor. The best I can do is:
function! Fvis()
normal! gv
cursor(1, 1)
endfunction
nnoremap <F9> <ESC>:call Fvis()<CR>gv
Upvotes: 1
Reputation: 90912
Look at the help for mode()
. The relevant part:
v Visual by character V Visual by line CTRL-V Visual blockwise
You need to be checking mode() == "\<C-V>"
(literal ^V
character), not mode() == "v"
, to check for blockwise visual mode.
Upvotes: 11