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

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 :w produces E45: 'readonly' option is set and 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 noreadonly removes 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 for vim -R {file}
  • Use :sview when you want a read-only reference panel next to a file you are editing

Next

How do I refresh the diff highlighting in Vim when it becomes stale after editing?