In VIM, is there a way to bind a key to a shell command? For example when F3 is pressed git commit -a -m "test" should be executed.

  • 1
    Note: there are vim extenstions like vim-fugitive that provides shortcuts for git commans. – pbm Mar 13 '12 at 11:18
  • 1
    Despite the existence of plugins, there is something to be said for learning how to do it yourself. – alesplin Mar 13 '12 at 19:07

Try map <F3> :!sh -xc 'git commit -a -m "test"'.

  • 6
    Why bother going through sh rather than just :!git commit -am "test"? – Kevin Mar 13 '12 at 14:11
  • @Kevin: I'm sorry, but I don't know the difference. I just used to do it this way. AFAIK they have no difference, But I'm going to wait for better answer. Thanks to your question. – xanpeng Mar 14 '12 at 5:16
  • 1
    You should probably use nmap, otherwise pressing <F3> in insert mode will insert the right hand side as text. Consider nnoremap, so that plugins can't override your binding. Also you can use <silent>, as in nnoremap <silent> <F3> :git commit -am 'test' if you just want to run the command without echoing it. See :he map. – Edd Steel Mar 14 '12 at 18:16
  • 1
    nnoremap does not protect bindings from being overridden. nnoremap means that the RHS will use the default meanings of vim keys and not user redefined ones: nmap / :echo "foo"<CR>/ will do an infinte recursion echoing foo, nnoremap / :echo "foo"<CR>/ will echo foo once and start a search – aktivb Dec 20 '12 at 23:39
map <F3> :!git commit -a -m "test" <enter>

Building on other answers, this removes the redundant invocation of sh and launches the command without having to press enter.

I was looking for this and couldn't find, also I cannot comment, so I made it an answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.