Introduction
Vim prevents accidental data loss by refusing to quit when there are unsaved changes, and refuses to write when the file is read-only. These errors compound when you have made changes to a read-only file:
E37: No write since last change (add ! to override)
E45: 'readonly' option is set (add ! to override)
E212: Can't open file for writingThe file may be read-only due to file permissions, opened with view instead of vim, or loaded from a version control system in read-only mode.
Symptoms
:qfails with "No write since last change":wfails with "readonly option is set" or "Can't open file for writing":wqfails with the same errors- File permissions show
-r--r--r--(read-only) - Vim status line shows
[readonly]at the bottom
Common Causes
- File has read-only permissions on disk
- File opened with
vim -Ror theviewcommand - File is part of a Git repository with
core.fileModerestrictions - File opened via a read-only file system (CD-ROM, mounted NFS with ro option)
- User accidentally set
:set readonlyduring editing
Step-by-Step Fix
- 1.Force write the file if you have write permission:
- 2.```vim
- 3.:w!
- 4.:q
- 5.
` - 6.The
!overrides the readonly warning. This only works if the file is actually writable. - 7.Remove the readonly option and then save:
- 8.```vim
- 9.:set noreadonly
- 10.:w
- 11.:q
- 12.
` - 13.Fix file permissions from within Vim using sudo:
- 14.```vim
- 15.:w !sudo tee %
- 16.
` - 17.This writes the file as root, then you can quit with
:q!. - 18.Fix file permissions from the shell:
- 19.```bash
- 20.chmod u+w myfile.txt
- 21.# Then in Vim
- 22.:w
- 23.:q
- 24.
` - 25.Discard changes and quit if you want to abandon your edits:
- 26.```vim
- 27.:e! " Reload the file from disk, discarding changes
- 28.:q " Now quit works because there are no unsaved changes
- 29.
` - 30.Or force quit without saving:
- 31.```vim
- 32.:q! " Quit without saving (changes are lost)
- 33.
` - 34.Write to a different file if you cannot modify the original:
- 35.```vim
- 36.:w /tmp/myfile-edited.txt
- 37.:q
- 38.
`
Prevention
- Check file permissions before editing:
ls -la filename - Use
sudoeditinstead ofsudo vimfor editing files that require root permissions - Add
set readonlyto your.vimrconly for specific filetypes if needed - Use Git's
git commit -ato stage and commit changes instead of relying on file permissions - Set up proper file ownership so your user account can edit the files you need to
- Use
:set autoreadto automatically reload files that change on disk from outside Vim - For configuration files in
/etc/, always usesudo vimorsudoedit