More than once I’ve opened file for edition, made my changes and tried saving to learn that it’s
A) read-only (Vim actually let’s you know as soon as you open it)
B) privileged, and my user without elevation didn’t have the rights
A is easy,
:w!, there, done. So, often I don[t pay heed to Vim’s warning here.
B however bites you right then and there. You hit save and learn Vim can’t open the file for writing. Even with forced save (
:w!). At first I copied the changes, reopened file again and applied them. But, for quite some time I’ve been using this little gem and since even during Anonymous Admin meetup it was met with loud ovation, I’m publishing it, for apparently it’s not so known:
:w !sudo tee %
Which roughly translates to:
write result of the command with current buffer as parameter.
Command is elevated
tee - read from standard input and write to standard output and files
Standard input is
% which in Vim-parlance means “current buffer”. AKA, what you would copy and paste.