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

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 produces E21: Cannot make changes, 'modifiable' is off
  • :set nomodifiable affects 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 nomodifiable to lock only the buffer-local copy (safest approach in plugins or autocmds)
  • Pair with :set readonly if you also want write-protection: readonly prevents :w, while nomodifiable prevents in-buffer changes
  • Plugin authors often use nomodifiable for UI buffers (file trees, logs, status panes) to prevent user accidents
  • modifiable! toggles the setting, which is useful for a quick lock/unlock keybinding

Next

How do I create a Vim mapping where the keys it produces are computed dynamically at runtime?