How do I prevent accidental edits to a buffer by making it completely read-only?
Answer
:set nomodifiable
Explanation
:set nomodifiable locks a buffer so that no changes can be made at all — not even temporary ones. This is stricter than :set readonly, which only warns when you try to write the file but still lets you edit in memory. nomodifiable is what Vim itself uses for help pages and quickfix windows.
How it works
:set modifiable— default state; buffer can be edited freely:set nomodifiable— disables all editing operations in the buffer; any attempt to insert, delete, or change text producesE21: Cannot make changes, 'modifiable' is off:set nomodifiableaffects only the current buffer; other buffers are unaffected
Example
:set nomodifiable " lock the buffer
i " trying to enter insert mode shows E21 error
:set modifiable " unlock when you're done reviewing
You can also toggle it from a mapping:
nnoremap <leader>l :setlocal modifiable!<CR>
Tips
- Use
:setlocal nomodifiableto lock only the buffer-local copy (safest approach in plugins or autocmds) - Pair with
:set readonlyif you also want write-protection:readonlyprevents:w, whilenomodifiableprevents in-buffer changes - Plugin authors often use
nomodifiablefor UI buffers (file trees, logs, status panes) to prevent user accidents modifiable!toggles the setting, which is useful for a quick lock/unlock keybinding