9

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.

amin
  • 3,672
  • 5
  • 33
  • 61

1 Answers1

16

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.

Kent
  • 189,393
  • 32
  • 233
  • 301
  • Good idea. But this appears to call `yourConditionExpression` only once - when the .vimrc file is read. For example, if the mapping is `nnoremap MyFunc == 0() ? ':Yep' : 'Nope'`, then once the keybinding is read, pressing F12 always returns the same result, even though executing `:echom MyFunc()` returns different results. – Brent Faust Feb 14 '19 at 00:46
  • @BrentFaust try `nnoremap MyFunc()` and let your `MyFunc()` return the key strokes (characters). I didn't test though. But it should not be a problem, since in my settings I have `getchar()` in function, if it is gonna be evaluated only once, it won't work. – Kent Feb 14 '19 at 09:47
  • You're correct - it _always_ calls the function. It's just that there were errors in my function that needs to change the focused pane: `exe "normal! \l"` gives the error *E523: Not allowed here* (in a noremap ). – Brent Faust Feb 14 '19 at 16:17