0

I'd like to insert the output from :history into the current buffer or alternatively write it to file. Is this possible?

2

2 Answers 2

1

I have a little Load command in my vimrc that will insert the output of any command in the buffer:

command -complete=command -nargs=+ Load call(
    \ (getline(1, '$')->filter((_, v) => len(v) > 0)->len() == 0 ? 'setline' : 'append'),
    \ ['.', execute(<q-args>)->split('\n')])

You can then use :Load history (or any other command).


This command looks a bit arcane; let's use a simpler version of the same:

command -complete=command -nargs=+ Load append('.', execute(<q-args>)->split('\n'))

It calls execute() on <q-args>, which expands to the command arguments (history in :Load history) with quotes, it then splits this on newlines with ->split('\n'). append() adds lines to the buffer after the current line (indicated by .).

This works well except for a small issue: if the buffer is currently empty you will end with an empty line at the top, because it "appends after the current line". This is what you want if there's already text in your buffer, but not when it's empty.

So the first line in that command:

(getline(1, '$')->filter((_, v) => len(v) > 0)->len() == 0 ? 'setline' : 'append')

Finds the appropriate command to use: getline(1, '$') gets all lines in the buffer, the filter removes empty lines, and if the number of lines if 0 it uses setline(), which sets the current line, overriding any text. Otherwise it will use append().

It's kind of a minor thing, but makes it a little bit nicer :-)


There are simpler ways to do the same, such as :put =execute('history') as filbranden mentioned in the commands, but it's not as "nice" as it's quiet a bit more typing and it leaves a blank line on top.

2
  • Just a note that => is from vim9 syntax
    – D. Ben Knoble
    Jun 3, 2022 at 14:09
  • Oops, I thought there wasn't any Vim9 syntax in there @D.BenKnoble, but I missed that one. I just remembered I posted that same command before, so people can use that version for older Vims or Neovim. Jun 3, 2022 at 15:10
1

There is always more than one way to do something but you can simply open command-line window (e.g. by pressing q: in Normal) and then copy/paste its contents as usual.

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.