5

I am trying to write register 0, into a file.

One method that I have found is to use redir:

redir! /tmp/3
echo 'hello'
redir end 

which gives me error invalid argument /tmp/3 and I don't know how to fix that.

Another thing I have found is to use writefile:

let g:the_buffer_raw = getreg("0")
call writefile([g:the_buffer_raw], "/tmp/3", "S")

The problem here is that vim doesn't just do what it says that it does. It does more than just write to the file. It removes the newlines from the register as well. And in the help it does say that it removes the newlines as well, but doesn't say how to change. So it's really just moving my problem from A to B.

I have been searching for hours now, wading through multiple miscellaneous solutions that at the end of the day, aint.

How do I setup a command in the .vimrc file which writes register zero to a file upon request?

D. Ben Knoble
  • 26,070
  • 3
  • 29
  • 65
john-jones
  • 235
  • 2
  • 11

2 Answers2

7

Have you tried to obtain the register as a list instead? See :h getreg()

:call writefile(getreg('0', 1, 1), ....)

PS: temporary filenames are best obtained with tempname()

Now, let's put this into a command. Sorry, I'll dot some dirty things.

command! 
\ -count=0 -nargs=? 
\ -complete=file 
\ DumpRegister 
\ echo 'call writefile(getreg("<count>", 1, 1), empty(trim("<args>"))?tempname():trim("<args>"))'
  • The register number is passed through the count, by default, it's "0, use :2DumpRegister to use another register for instance.
  • The filename is an optional parameter to the function, a temporary filename is used otherwise
  • I've used :echo to test the command. Remove it to have the final command.

BTW, there is a last issue: when the filename is tempname(), we don't know which one is used... hum... I have another convoluted idea. Let's use a lambda.

command! 
\ -count=0 -nargs=? -complete=file 
\ DumpRegister 
\ echo { f-> printf('Register %d dumped into %s: %s', <count>, f, 'call writefile(getreg("<count>", 1, 1),f)')}(empty(trim("<args>"))?tempname():trim("<args>"))

Remove the two single quotes around the call to writefile().

=>

:DumpRegister
:5DumpRegister
:DumpRegister foobar-reg0.txt
:9DumpRegister foobar-reg9.txt
Luc Hermitte
  • 17,351
  • 1
  • 33
  • 49
6

To redirect to a file, you need to use >

:redir! > /tmp/3

See :help :redir for more details.

To use this to write the contents of register "0 into /tmp/3:

:redir! > /tmp/3
:echo @0
:redir END
Rich
  • 31,891
  • 3
  • 72
  • 139