view on CentOS

When editing a file, it’s often handy to have a related file open for reference. For example, if I’m using a library function I might have the function definition open in a separate window. Or if I’m editing a configuration file on one server, I might want to see what the same configuration file looks like on a different server.

Vim has a read-only mode (vim -R) that is perfect for this purpose. From the vim man page:

Read-only mode. The ‘readonly’ option will be set. You can still edit the buffer, but will be prevented from accidently overwriting a file. If you do want to overwrite a file, add an exclamation mark to the Ex command, as in :w!. The -R option also implies the -n option.

The -n option stands for “no swap file” — since you will not be editing the file, there is no reason to create a swap file. This is a helpful because it allows you to open a file in read-only mode multiple times and vim will not complain.

Instead of typing vim -R, I typically invoke vim using the view command, which does the same thing:

Vim behaves differently, depending on the name of the command (the executable may still be the same file).

vim
The “normal” way, everything is default.

view
Start in read-only mode. You will be protected from writing the files. Can also be done with the -R argument.

On Ubuntu, vi, vim, and view are all symlinks managed by the alternatives system. When the vim package is installed, all three commands point at the real binary, /usr/bin/vim.basic. Since all three commands invoke the same binary, the behavior is consistent across commands (except view invokes vim in read-only mode, as expected).

On CentOS, the situation is more complicated. The vim-minimal package provides /bin/vi and /bin/view, and the latter is just a symlink to the former. The vim-enhanced package provides /usr/bin/vim, then sets up a bash alias vi=vim in /etc/profile.d/vim.sh. Unfortunately, there is no special treatment for the view command, so when you invoke vi or vim you get the enhanced vim, but when you invoke view you get the minimal vim. This can be annoying — for example, if you open a file using vi or vim you will get syntax highlighting, but if you open a file using view, you won’t.

Fortunately, the fix is fairly simple. Just add the following lines to your .bashrc:

if [ -x /usr/bin/vim ]; then
    alias view='vim -R'
fi

This sets up an alias for the view command, so vi, vim, and view all invoke the same binary and the behavior is consistent across all three.