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

How do I make a buffer completely read-only and unmodifiable?

Answer

:setlocal nomodifiable

Explanation

While :set readonly prevents accidental writes, nomodifiable goes further by preventing any changes to the buffer contents entirely. Even :s, dd, or insert mode will fail. This is useful for reference buffers, output displays, or preventing accidental edits.

How it works

  • :setlocal nomodifiable — prevents any changes to the buffer
  • :setlocal modifiable — re-enables editing
  • Different from readonly: readonly only prevents :w, while nomodifiable prevents all edits
  • Attempting to edit shows: E21: Cannot make changes, 'modifiable' is off

Example

" Make a reference file read-only
:edit reference.txt
:setlocal nomodifiable

" Create a read-only output buffer
:enew | setlocal nomodifiable buftype=nofile
Attempting dd or i on a nomodifiable buffer:
E21: Cannot make changes, 'modifiable' is off

Tips

  • Use in autocmds: autocmd BufRead *.log setlocal nomodifiable
  • Temporarily enable edits: :setl ma (short for modifiable), edit, then :setl noma
  • Combine with noswapfile for true read-only buffers
  • buftype=nofile plus nomodifiable creates a display-only buffer

Next

How do I return to normal mode from absolutely any mode in Vim?