VIM: Conditional Key Mapping

Viewed 1577

In Vim I want to have a conditional statement in a Key mapping.

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 )

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.

Thanks!

1 Answers

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. Here's an example from the vim wiki:

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

This example conditionally maps Esc to either C-e or Esc depending on whether or not the pumvisible() function returns a true or false value. 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 <C-o>, and drop the trailing a or i.

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

In insert mode C-o lets you run one normal mode command, then returns to insert mode. Since your normal mode command does not move the cursor, your should be returned to insert mode where you started.

Related