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:readonlyonly prevents:w, whilenomodifiableprevents 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
noswapfilefor true read-only buffers buftype=nofileplusnomodifiablecreates a display-only buffer