VIM save with sudo

A colleague of mine did the mistake of opening a file in vim without using sudo and when he was going to save the file he did not have permissions to do it.

He then googled and found a way to save the file without reopening the file and retyping the changes.

When saving a file in vim you use the :w command, and without any parameters it will save the buffer to the current file. You could also type a filename as parameter which would act like a "save as" leaving the current file unchanged.

You can also type:

:w !sudo sh -c "cat > %"

What is happening here is when using a command as a parameter to :w the buffer is sent as input to that command, which will be captured by cat and then written to %, the percent sign is a symbol for the current file.

You can also add this mapping to your .vimrc file for a nice shortcut

cmap w!! w !sudo sh -c "cat > %"