Is there any way to map leader-r to repeat last command sent to bash?

For example, when working with C files I would like to compile and run program from vim without typing :!make or gcc.

I know I can bind specific command to the key but it won't work for other types of files.

2 Answers 2


The :!! command repeats the last :!{cmd}. It's even available in venerable ol' vi.


Edit: Ingo Karkat's answer is much better. ... I would delete this post if it wasn't accepted (which means I can't).

Here's one solution. It only searches the last 100 commands, obviously, you could change this number (History indexing starts at -1, which is the last command you typed, so the lower the number, the further is searched).

fun! LastCommand()
        let l:i = -1
        while l:i > -100
                let l:cmd = histget("cmd", l:i)
                if strpart(l:cmd, 0, 1) == "!"
                        let l:i = 1
                        execute l:cmd
                let l:i -= 1

        if l:i < 1 | echoerr "No command found" | endif
nnoremap <Leader>r :call LastCommand()<CR>
  • I'd rather not delete this since if I do, that will leave a question unanswered. I have upvoted Ingo's answer which now has more votes than yours. Given the disclaimer you have added, deletion seems a bit harsh. You never know who might find this useful. If you feel so strongly about it, leave a comment to the OP asking them to accept Ingo's answer instead. Then, if you still wish to, you can delete yours.
    – terdon
    Mar 10, 2015 at 22:50

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .