6

I want to write to a file in the home directory, so I tried the following command:

:call writefile(["foo"], "~/event.log", "a")

But I got an error:

E482: Can't create file ~/event.log

I am pretty sure that I have write permission for my home directory (of course), and there is not a file with the same name at the specified path.

If I change the destination path to the current path, it works.

Does anyone know what the problem is?

2
  • 5
    Please don't use screenshots for the commands you tried, but post them as text. This makes it easier to test them because the can be copied and pasted. Commented Sep 23, 2020 at 6:03
  • 1
    You might also like github.com/habamax/vim-godot although I didn't put ctags extension there (it is just in my .ctags)
    – Maxim Kim
    Commented Sep 23, 2020 at 6:40

2 Answers 2

15

The tilde is only treated specially if it's used in commands like :w ~/event.log. When used in a string that is passed to a function -- even if this function treats the string argument as a file name -- it has no special meaning. You have to take care of the expansion of the tilde to the home directory yourself.

Vim has an expand() function that can be used for this. So one way to correctly write a file in your home directory is to execute the following command:

call writefile(["foo"], expand("~/event.log"), "a")
3
  • It works! Thanks for your answer and explanations.
    – naive231
    Commented Sep 23, 2020 at 12:10
  • @D.BenKnoble You mean the example in the help file? That does not use a tilde. Commented Sep 23, 2020 at 12:37
  • @JürgenKrämer doh... this is why I prefer text 😂
    – D. Ben Knoble
    Commented Sep 23, 2020 at 12:41
6

As Jürgen Krämer said, '~' string won't be interpreted by most vim functions.

Thus, when receiving the string from elsewhere, we may indeed need to expand() the tilde. However, when directly working on hardcoded pathnames as in your MWE, we can also use $HOME as in

call writefile(['foo'], $HOME.'/event.log'), 'a')

Your Answer

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

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