2

How can I map a sequence in vim conditionally to run any of two external programs in such way that the screen is not cleared to show the else clause?

For example:

:nmap <c-l> :if filereadable('Makefile')<CR>!make<CR>else<CR>!ls<CR>endif<CR>

ctrl+m executes make but then clears the screen and prints the following at the bottom of it:

:  else
:  !ls
:  endif
Press ENTER or type command to continue
n.r.
  • 1,900
  • 15
  • 20

2 Answers2

9

You can use an expression mapping (:help map-expr)

:nnoremap <expr> <c-m> filereadable('Makefile') ? ':make<CR>' : ':!ls<CR>'

Notes:

  • You should use :noremap; it makes the mapping immune to remapping and recursion.
  • <C-m> is the same as <CR>; there's currently no way to distinguish the two; better use different keys. See this answer for more information.
Community
  • 1
  • 1
Ingo Karkat
  • 167,457
  • 16
  • 250
  • 324
3

you need map <expr>

e.g.:

nnoremap <expr> <c-t> line('.')>=6? ':!ls<cr>' : ':!seq 10<cr>'

in your example:

:nnoremap <expr> <c-m> filereadable('Makefile') ? ':make<CR>' : ':!ls<CR>'

for detail info:

:h :map-<expr> 

note that, if you map <c-m>, the Enter will follow that mapping too. better use another key combination, unless you intend to do so.

Kent
  • 189,393
  • 32
  • 233
  • 301