简体   繁体   English

VIM:条件密钥映射

[英]VIM: Conditional Key Mapping

In Vim I want to have a conditional statement in a Key mapping. 在Vim中,我希望在Key映射中有一个条件语句。

If the cursor is at the start of a line, I want this mapping: 如果光标位于一行的开头,我想要这个映射:

imap <F1> <ESC>:syntax sync fromstart<CR>i

but otherwise have this mapping (the only difference is the final character) 但否则有这个映射(唯一的区别是最终字符)

imap <F1> <ESC>:syntax sync fromstart<CR>a

In the second mapping the cursor is not put back into the correct place if this mapping is run when the cursor is at the start of a line (when we go back into insert mode with the a ) 在第二个映射中,如果在光标位于行的开头时运行此映射(当我们返回带有a的插入模式时),则光标不会放回到正确的位置。

I'm trying to find for a solution to this specific problem, but I also want to know if you can indeed you put a conditional in a Vim keymapping. 我正在尝试寻找这个特定问题的解决方案,但我也想知道你是否确实可以在Vim键映射中添加条件。

Thanks! 谢谢!

The answer to your general question is: Yes, mappings can contain conditional logic. 您的一般问题的答案是:是的,映射可以包含条件逻辑。 You can do this in a few ways, the simplest is to use an <expr> mapping. 您可以通过几种方式执行此操作,最简单的方法是使用<expr>映射。 Here's an example from the vim wiki: 这是vim wiki的一个例子:

inoremap <expr> <Esc>      pumvisible() ? "\<C-e>" : "\<Esc>"

This example conditionally maps Esc to either Ce or Esc depending on whether or not the pumvisible() function returns a true or false value. 此示例有条件地将Esc映射到CeEsc,具体取决于pumvisible()函数是否返回true或false值。 In your case you would need to find (or define) an expression that determines where the cursor is on the line. 在您的情况下,您需要找到(或定义)一个表达式,该表达式确定光标在该行的位置。

Another option is to just write a function that contains all of the logic and map the key to that function rather than an expression. 另一个选择是只编写一个包含所有逻辑的函数,并将键映射到该函数而不是表达式。

In your specific case none of this is necessary. 在您的具体情况下,这一切都不是必需的。 Just replace the <Esc> in your mapping with <Co> , and drop the trailing a or i . 只需用<Co>替换映射中的<Esc> ,然后删除尾随ai

imap <F1> <C-o>:syntax sync fromstart<CR>

In insert mode Co lets you run one normal mode command, then returns to insert mode. 在插入模式下, Co允许您运行一个普通模式命令,然后返回插入模式。 Since your normal mode command does not move the cursor, your should be returned to insert mode where you started. 由于普通模式命令不会移动光标,因此您应该返回到已启动的插入模式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM