问题
I'm following Mapping keys in Vim - Tutorial (Part 1) - 6.2 Insert mode maps, and there it says:
The <C-R>= command doesn't create a new undo point.
You can also call Vim functions using the <C-R>= command:
:inoremap <F2> <C-R>=MyVimFunc()<CR>
I'm trying to use this to call SingleCompile#Compile()
like:
map! <F5> <C-R>=SingleCompile#Compile()<CR>
It's working, but the problem is that when I get back to insert mode, a 0
character is inserted as a side-effect.
Why is this and how can I avoid it?
EDIT:
I'm using <C-R>
because it doesn't create a undo point and has the purpose of calling a function instead of entering a command like <C-O>
does. I don't want to create a undo point.
EDIT:
I've updated the VIM wiki based on the ternary operator trick provided by Ingo Karkat.
回答1:
The implicit return value of a function is 0
. You need to either modify SingleCompile#Compile()
or write a wrapper that returns the empty string:
function! SingleCompileWrapper()
call SingleCompile#Compile()
return ''
endfunction
map! <F5> <C-R>=SingleCompileWrapper()<CR>
An alternative clever trick is to evaluate the function inside the ?:
ternary operator:
map! <F5> <C-R>=SingleCompile#Compile()?'':''<CR>
回答2:
The '0' is the return value of the function, which is naturally inserted into the buffer when called in insert mode
Use <C-O> instead of <C-R> to leave the insert mode for the comand
回答3:
I wouldn't recommend that approach, but how about the redneck solution (just delete the 0
after-the-fact):
map! <F5> <C-R>=SingleCompile#Compile()<CR><BS>
Seriously, for those situations where <C-R>
cannot be used, and you have to leave insert mode, :undojoin
may help.
来源:https://stackoverflow.com/questions/11686210/vim-single-compile-command-from-insert-mode