How to save a file in Vim
Press Esc to get to Normal mode, then type :w and press ↵. To save under another name, type :w newname.txt instead.
Saving is the :w command, short for "write". Like every command that starts with a colon, it only works from Normal mode: if the bottom line says -- INSERT --, press Esc first, or the :w goes into your text. As you type the colon, the cursor jumps to the bottom line; ↵ (Enter) runs the command, and Vim confirms with the file name, its line count and written.
| Type | What it does |
|---|---|
:w ↵ | Save the file. |
:w notes.txt ↵ | Save a copy as notes.txt. You keep editing the original file. |
:saveas notes.txt ↵ | Save as notes.txt and carry on editing notes.txt from now on (:sav for short). |
:w! ↵ | Save even though the file is marked read-only (if the system lets you write it). |
:up ↵ | Save only if something changed (:update), so the file's modified time stays put otherwise. |
:wa ↵ | Save every open file that has changes. |
:wq ↵ or ZZ | Save and quit. ZZ saves only if something changed. |
:5,20w part.txt ↵ | Save only lines 5 to 20 to another file. |
:w !sudo tee % ↵ | Save a file you opened without permission to write it (Vim only; see below). |
Practise saving
Type the keys for each one, as you would in Vim. Nothing here touches a real file.
Opened a system file without sudo?
You edited /etc/hosts, and :w says E45: 'readonly' option is set or E212: Can't open file for writing: you don't have permission, and :w! won't help. In Vim you can still save without starting over:
:w !sudo tee % > /dev/null and ↵
:w !command sends the buffer to a shell command instead of a file, sudo tee writes what it receives with administrator rights, and % stands for the current file name. Type your password when sudo asks. Vim then notices the file changed outside it and asks whether to load it; the saved file is already right either way.
In Neovim this trick doesn't work, because Neovim runs :! commands without a terminal, so sudo can't ask for your password. Save to a place you can write instead, :w /tmp/hosts, and copy it over with sudo from a shell. Next time, open it with sudoedit /etc/hosts: sudo gives your editor a temporary copy to edit as yourself, and puts it back in place when you quit.
:w name or :saveas?
Both write the text to a new file. The difference is which file you are editing afterwards. After :w copy.txt, you are still editing the original, so the next :w saves there; it is a quick backup. After :saveas copy.txt, the buffer now belongs to copy.txt, the way Save As works in other programs. If the new name already exists, both refuse with E13: File exists; add ! (:w! copy.txt) to overwrite it.