我正在尝试编写一个有条件地改变回车键行为的vim函数。我希望输入键有时缩进,其他时候表现为“正常”。通常我的意思是,如果一系列案例不适用,就像函数/映射一样不存在。我遇到的麻烦是我使用<CR>
作为调用函数的触发器,因此我不确定如何只说“哦,这些情况都不适用,执行{{ 1}}好像这个映射从未被定义过。“
作为一个例子,请考虑我的<CR>
,如果以.vimrc
开头,则会缩进该行,否则会触发回车。 (我的vimscript非常新手,所以这个功能可能不正确,但我认为这个想法仍然存在......)
a
这与我实际尝试的内容相比有所简化,但概念是相同的。我正在寻找一种方式来说“我的if语句都没有应用,就像这个映射不存在一样”。有没有办法做到这一点?
答案 0 :(得分:1)
您需要为映射指定<expr>
标记。有了这个,映射的右侧将被计算为表达式。
以下是从我的配置中获取的示例,其中我返回不同命令的不同提示:
cnoremap <expr> <CR> CCR()
" make list-like commands more intuitive
function! CCR()
let cmdline = getcmdline()
command! -bar Z silent set more|delcommand Z
if cmdline =~ '\v\C^(ls|files|buffers)'
" like :ls but prompts for a buffer command
return "\<CR>:b"
elseif cmdline =~ '\v\C/(#|nu|num|numb|numbe|number)$'
" like :g//# but prompts for a command
return "\<CR>:"
elseif cmdline =~ '\v\C^(dli|il)'
" like :dlist or :ilist but prompts for a count for :djump or :ijump
return "\<CR>:" . cmdline[0] . "j " . split(cmdline, " ")[1] . "\<S-Left>\<Left>"
elseif cmdline =~ '\v\C^(cli|lli)'
" like :clist or :llist but prompts for an error/location number
return "\<CR>:sil " . repeat(cmdline[0], 2) . "\<Space>"
elseif cmdline =~ '\C^old'
" like :oldfiles but prompts for an old file to edit
set nomore
return "\<CR>:Z|e #<"
elseif cmdline =~ '\C^changes'
" like :changes but prompts for a change to jump to
set nomore
return "\<CR>:Z|norm! g;\<S-Left>"
elseif cmdline =~ '\C^ju'
" like :jumps but prompts for a position to jump to
set nomore
return "\<CR>:Z|norm! \<C-o>\<S-Left>"
elseif cmdline =~ '\C^marks'
" like :marks but prompts for a mark to jump to
return "\<CR>:norm! `"
elseif cmdline =~ '\C^undol'
" like :undolist but prompts for a change to undo
return "\<CR>:u "
else
return "\<CR>"
endif
endfunction