vimtricks.wiki Concise Vim tricks, one at a time.

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

  • cnoreabbrev defines an abbreviation in Vim's command-line mode
  • w!! is the trigger text you type after :
  • w !sudo tee > /dev/null % pipes the current buffer to sudo tee and writes to % (current file)
  • > /dev/null suppresses 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 :w habit for regular files, and reserve :w!! for permission exceptions
  • You can pair this with set confirm so accidental writes prompt more clearly

Next

How do I continuously record and restore sessions with vim-obsession?