Maintain permissions bits when writing new file with VIM

file-permissionsunixvim

In Vim, when I write a copy of the current buffer to a new file using :w [filename], it appears that Vim uses the default (i.e. set by umask or whatever) file permissions for the new file. If the current buffer was loaded from an existing file, though, shouldn't the "right" behavior be to duplicate the permissions from that file? For example, if I'm editing an executable file, and I write a new copy of the file, why doesn't Vim write a new executable? Is there any way to force Vim to behave the way I'm describing, other than just doing something like ! chmod --reference % [newfilename] after writing the new file?

Best Answer

You could do something like this. First, capture the name of the original file.

au BufRead * let b:oldfile = expand("<afile>")

Then, when you save the new file, change its permissions to be the same as those of the original file.

au BufWritePost * if exists("b:oldfile") | let b:newfile = expand("<afile>") | if b:newfile != b:oldfile | echo system("chmod --reference=".b:oldfile." ".b:newfile) | endif |endif

Just put both of those autocommands into your ~/.vimrc.

Related Question