Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write a conditional mapping in VIM?

I want to do nnoremap Q :q!<cr> and nnnoremap Q :bd<CR>, how can i mix these two bindings?
What i ideally want is to make the Q binding smart enough to know when we are in a buffer, and when this is the last buffer in the window.

like image 462
amin Avatar asked Feb 03 '17 12:02

amin


People also ask

What is key mapping in Vim?

Key mapping refers to creating a shortcut for repeating a sequence of keys or commands. You can map keys to execute frequently used key sequences or to invoke an Ex command or to invoke a Vim function or to invoke external commands. Using key maps you can define your own Vim commands.

Do I need to save the map command in Vim?

If you want to map a key for only one Vim session temporarily, then you don't need to save the map command in a file. When you quit that Vim instance, the temporary map definition will be lost. If you want to restore the key maps across Vim instances, you need to save the map definition command in a file.

How to customize Vim?

One way you can customize vim is by creating your own key mappings to make Vim yours. This article will show you basics of map. This is not 100% comprehensive, but should be enough to get you started. Now whenever you type x, it executes dd instead. When you type x, it will no longer do dd. It is back to its original function.

What are conditionals and loops in vimscript?

A basic program consists of conditionals and loops. In this chapter, you will learn how to use Vimscript data types to write conditionals and loops. Vimscript relational operators are similar to many programming languages: Recall that strings are coerced into numbers in an arithmetic expression.


1 Answers

The map <expr> (:h map-<expr>) is your friend.

nnoremap <expr> Q yourConditionExpression ? ':q!<cr>':':bd<cr>'

In above

yourConditionExpression

could be an boolean expression E.g. 3>0 or a function returns boolean. You can put the checking logic in there.

like image 165
Kent Avatar answered Sep 28 '22 07:09

Kent