Oops, I forgot to sudo in Vim
It’s a huge annoyance when I’m hammering away in Vim, being extremely productive as always
, and I get to a proper saving point and I get the ‘readonly’ option is set (add ! to override) message. This message drives me bonkers because it means I am going to have to take a few extra steps in order to save my hard work. Whether it be a quick copy-paste-copy-paste, or whatever method you prefer, it is still a very annoying process that I wish there was a quick fix for.
Lo and behold, there is a knight in shining armor for this very issue. Meet my friend “tee”. Since Vim has the ability to run commands from within itself, we can use tee to take our file from Vim and write to the file with sudo, which is what we forgot to do in the first place. All you need to do is place this small snippet in your .vimrc:
What this does is map the vim command :w!! to the command that follows it, which uses tee to take the file from stdin and write to the file with root privileges. Once the command runs you can reload the file you were writing, although you will still not have write privileges so every time you want to write you can just use this command again or drop out real fast and open up Vim with sudo. Not a perfect solution, I should probably just remember to sudo when I need to :p , but it works in a pinch and makes my file editing slightly less annoying.