5

I'd like to be able to view the last n commands, similar to the history command in bash, and then be able to execute the nth command similar to the way it is done in bash by using !<command number> is there an equivalent to this in vim?

  • 9
    No direct equivalent, but try q: in normal mode (:h command-line-window for details). You can also edit commands before re-running them from there. A most useful command, along with q/. – Sato Katsura Jun 15 '16 at 17:26
1

This is highly hacky but should work:

function! ReExecute(historyNumber)
  " Open the command window
  call feedkeys('q:', 'in')

  " Jump to the desired line
  call feedkeys(a:historyNumber.'gg', 'tn')

  " Execute the command
  call feedkeys("\<CR>", 'tn')
endfunction

command! -nargs=1 R call ReExecute(<f-args>)

Now use R 2 to replay the command at line 2.

Thanks for user9433424 for his answer.


Edit: It seems a little hard to use like this, because you execute the command without seeing it, hence this little modification:

function! ReExecute(historyNumber)
  " Open the command window
  call feedkeys('q:', 'in')

  " Jump to the desired line
  call feedkeys(a:historyNumber.'gg', 'tn')

  " Copy the current command and quit
  call feedkeys("y$:q\<CR>", 'tn')

  " Add the value into the command line
  call feedkeys(':'.@", 'tn')
endfunction

command! -nargs=1 R call ReExecute(<f-args>)

This populate your command line with the nth last command, which is more what you asked in the first place anyway.

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.