Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VIM: Calling a function from insert mode with imap?

Tags:

vim

I have a function that I've written in my vimrc to turn syntax off and set paste. The function looks like this:

function! ToggleSyntax()
if g:syntaxon == 1
syntax off
set paste
let g:syntaxon = 0
else
syntax on
set nopaste
let g:syntaxon = 1
endif
endfunction

I use the F12 key to call the function, and have mapped the function to F12 like this:

map <F12> :call ToggleSyntax()<cr>
imap <F12> <c-o>:call ToggleSyntax()<cr>

the problem that I'm having is that I can't call the ToggleSyntax function from insert mode. This is very confusing to me, because I have used the imap handler, but still, this function only works from command mode. I can't figure out how to get it to work, any help with this would be greatly appreciated! thank you!

like image 905
pepper Avatar asked Feb 17 '23 16:02

pepper


1 Answers

For me, your function also turns paste on in insert mode, but it doesn't turn it back off (and syntax on). The reason is that when :set paste, no insert mode mappings apply. That's one essential aspect of 'paste', see also :help 'paste'.

The only way to toggle in insert mode is

:set pastetoggle=<F12>

(that option was explicitly made for this purpose) but then, you'll lose the parallel syntax toggling that your function provides.

like image 91
Ingo Karkat Avatar answered Feb 27 '23 07:02

Ingo Karkat