brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: view opens a file in Vim in read-only mode

Vim
~/tips/tip-vim-view-read-only

view /etc/fstab

Opens a file with Vim's navigation and search, but blocks accidental saves.

Sometimes I only want to read a config file with search and quick jumping, and I don’t want to risk typing into it by accident. A pager is limited. A normal editor session is risky.

view /etc/fstab

Starting Vim under the name view has the same effect as vim -R. The file opens with the readonly option set, so Vim refuses to write it with :w and shows a warning. You get search, folds, marks and everything else, without the file being at risk.

If you’re in Vim already and want the same protection for one file, :view file opens it read-only inside the current session.

The protection is light, which is the caveat. The buffer is still editable, and the docs say you can overwrite the file with :w!. Read-only mode only prevents accidents, it doesn’t enforce anything. For a file you really must not change, a root-owned file with no write permission for your user does that job. If the view command isn’t installed on your system, vim -R file does the same.

If you want to go a step further, vim -M means modifications in the text are not allowed. In a quick check with Vim 9.1, :echo &modifiable printed 0 under -M, and :echo &readonly printed 1 in a view session. I’d use view for reading and -M when even typing into the buffer would be annoying.

Further reading: Vim help: starting, -R and view

Going deeper: Guide: advanced tmux, a config that grows with you, formats, layouts and more

More Vim tips :%s/<Ctrl-r><Ctrl-w>/newname/g /oldname find . -name "*.conf" | vim – vim --clean file.txt :set textwidth=72 All Vim tips (45) All topics

Link