0

I want to write the contents of a buffer with writefile(). However I do not want to use binary mode because I suspect it has (undocumented) side effects.

My question concerns noeol files, i.e. files whose last line isn't terminated by an EOL.

If I set the nofixeol option, open a noeol file, and write it with :w, Vim writes the file as-is, i.e. without adding an EOL to the last line. This is what I expect.

However if I use writefile() instead of :w, Vim does add an EOL to the last line despite nofixeol. This isn't what I expect or want.

Using :w:

$ echo -n abc > foo
$ vim --cmd 'set nofixeol' foo
:wq bar
$ od -c bar
0000000    a   b   c

Using writefile():

$ echo -n abc > foo
$ vim --cmd 'set nofixeol' foo
:call writefile(getline(1,'$'), 'bar')
:q
$ od -c bar
0000000    a   b   c  \n

Is there a way to use writefile() on noeol files so it doesn't add an EOL to the last line (avoiding binary mode)?

Alternatively, what side effects does binary mode have? For one thing it adjusts expandtab, according to :h edit-binary. What else might it do?

Thanks!

  • Is there a reason, you cannot use writefile() with the b flag? You have to take care of adding the correct line terminators according to the fileformat option, but I believe this is what you need. – Christian Brabandt Dec 17 '18 at 7:43
2

The word binary here may be "scaring" you more than it should. The flag, the command line argument (-b) and the 'binary' option are closely related and have nothing to do with binary files except for setting up Vim so as to avoid accidentally corrupting such files. You can use them with non-binary files, too, if so inclined. It just disables certain options that can (possibly transparently) modify text/formatting. E.g. looking at :h 'bin':

'textwidth'  will be set to 0
'wrapmargin' will be set to 0
'modeline'   will be off
'expandtab'  will be off

Plus, 'fileformat' and 'fileformats' are disabled while reading files to prevent conversion.

Rather than causing the side effects you mention this state is meant to prevent them. So if you're just avoiding it because of such concerns my suggestion is to go ahead and use the writefile() "b" flag...it will prevent any unexpected edits from occurring as the file is written.

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.