How do I define w!! to save a root-owned file without reopening Vim?
Answer
cnoreabbrev w!! w !sudo tee > /dev/null %
Explanation
When you forget to open a file with elevated privileges, quitting and reopening can break your flow. A command-line abbreviation can turn :w!! into a sudo write-through command so you can save the current buffer in place. This is an advanced quality-of-life trick for system config edits where permission errors happen often.
How it works
cnoreabbrevdefines an abbreviation in Vim's command-line modew!!is the trigger text you type after:w !sudo tee > /dev/null %pipes the current buffer tosudo teeand writes to%(current file)> /dev/nullsuppresses duplicate output in the command area
After adding this to your config, typing :w!! expands to the full shell pipeline automatically.
Example
You edit a protected file:
/etc/hosts
A normal save fails with permission denied. Instead run:
:w!!
Vim asks for sudo credentials and writes the buffer to the same path without restarting your session.
Tips
- Use this only on trusted systems; it executes a shell command
- Keep your normal
:whabit for regular files, and reserve:w!!for permission exceptions - You can pair this with
set confirmso accidental writes prompt more clearly