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?

1
  • 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/. Jun 15, 2016 at 17:26

2 Answers 2

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.

1

I got my answer from here: Using command line history in vim

Here is a summary to execute your command of choice from command history:

  • q: (opens the command history window)
  • use vim browsing keys to go to the command you want to execute. Alternately :n where n is line number of the command to execute, will place you on the line.
  • CR -> (Carriage return) Press enter to execute the command.

If you want to run the last n commands:

  • q:
  • yank the number of commands you want to run
  • Press ctrlc twice
  • :@"
1
  • Welcome to Vi and Vim! One of our moderators has edited your question to format it (we use markdown, and there's special formatting applied to <kbd> tags).
    – D. Ben Knoble
    Oct 28, 2019 at 12:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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