Maintain permissions bits when writing new file with VIM

8

2

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?

Kyle Strand

Posted 2013-10-11T20:04:16.213

Reputation: 1 206

Possibly related: http://unix.stackexchange.com/q/58880/22703

– allquixotic – 2013-10-11T20:31:03.367

I think the answer is already in the question -- you should make a macro or keybinding that does that chmod for you. AFAIK, vim does not have this built in. – Kevin Panko – 2013-10-11T21:29:47.757

Answers

3

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.

garyjohn

Posted 2013-10-11T20:04:16.213

Reputation: 29 085

This answer is awesome, but I have one suggestion: change echo system( etc to silent echo system( etc. This avoids the "press ENTER to continue" hang. – Kyle Strand – 2013-10-18T23:16:09.330

@KyleStrand: I could have used call system(... to avoid printing anything to the display, too, but I was trying to avoid the problem of the command failing silently. If you don't think it will ever fail, or would rather live with the occasional failure rather than the pesky Press ENTER..., then I agree with your suggestion. I think a better solution, though, would be to write a function that captures the output of system() and echoes it only if it is not empty. I've done that in plugins and it works pretty well. – garyjohn – 2013-10-19T00:34:30.383

Fair enough. I don't understand vimscript very well at all, so I just stuck in "silent" to see if it would work, and when it seemed to be okay I just left my .vimrc like that. I'd definitely prefer the occasional failure to the persistent Press ENTER, though, so I think I'll either stick with silent or use call. Thanks again for the suggestions! – Kyle Strand – 2013-10-19T06:34:08.027

0

Make sure that there are no unsaved changes in the file and then use cp to make a copy. That will result in a copy with the same permissions as the original.

Roland Smith

Posted 2013-10-11T20:04:16.213

Reputation: 1 712