Save a File as Sudo Without Exiting Vim

Save a File as Sudo Without Exiting Vim

I have often opened a file which I did not first run as sudo in vim, edited the file, then to only find out that it is in read-only mode. I would then have to close the file then re-open it as superuser then make the changes needed. I found this to be very frustrating and found out there are several ways to get the file edited by inserting commands in command-mode using vim.

When editing a file that you don’t have permissions to run:

: !sudo tee %

You will then be asked to insert your password. Next you will be asked to click O(k) or L(oad) then enter. I have found either one will still write the file but L(oad) seems to take you back to the newly edited file while O(k) will take you to the file before you made the changes but once you make the new changes and exit, the changes will persist.

Using my custom .vimrc

Since I have found many tweaks that make vim even better, I have implemented one such tweak that allows me to save the file as sudo by running :w!!. My entire vim config can be found here my vim config (lines 178 and 179 for just the :w!! config).