How do I open a file in read-only mode so I cannot accidentally modify it?
Answer
:view {file}
Explanation
:view opens a file with the readonly option set, preventing accidental writes. Unlike :e, any attempt to save changes fails with a clear error message, making it ideal for browsing configuration files, logs, or reference material you should not modify.
How it works
:view {file}opens the file read-only in the current window:sview {file}opens it in a new horizontal split- Attempting
:wproducesE45: 'readonly' option is setand does nothing - All other operations work normally: searching, navigating, yanking, and visual selection
Example
:view /etc/hosts
You can search with /, copy lines with y, and navigate freely. Attempting :w fails safely without modifying the file.
:sview ~/.bash_profile
Opens your shell config in a split alongside your current buffer for quick reference.
Tips
- To edit after all:
:setlocal noreadonlyremoves the protection for the current buffer vim -R {file}from the shell opens Vim directly in read-only mode (same as:view)view {file}at the shell prompt is a shortcut forvim -R {file}- Use
:sviewwhen you want a read-only reference panel next to a file you are editing