Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does vim writes a read-only file?

Tags:

vim

Sorry for the newbie question. I would like to know, how vim manages to write a read-only file. I've 555 permissions on a text file. But, when I open & write something to it and does :w! , the changes I made to file are saved. I wonder how vim is doing this in background!!. Is it like changing permissions temporarily to 755 and writing to it and reverting the permissions back? Please enlighten.

like image 702
srand9 Avatar asked May 12 '16 08:05

srand9


1 Answers

EDIT: I originally answered with correct, but ultimately irrelevant information on how UNIX permissions work: that was not what Vim was doing.

Indeed, you're right: when you issue :w!, and you're on UNIX, Vim will add the write permission if it needs to:

/* When using ":w!" and the file was read-only: make it writable */
if (forceit && perm >= 0 && !(perm & 0200) && st_old.st_uid == getuid()
                 && vim_strchr(p_cpo, CPO_FWRITE) == NULL)
{
    perm |= 0200;
    (void)mch_setperm(fname, perm);
    made_writable = TRUE;
}

and subsequently reset it back:

if (made_writable)
    perm &= ~0200;      /* reset 'w' bit for security reasons */

It is also reflected in the help:

Note: This may change the permission and ownership of
the file and break (symbolic) links. Add the 'W' flag to 'cpoptions' to avoid this.

like image 163
Amadan Avatar answered Sep 29 '22 20:09

Amadan