Linux – vim and sudo vim use different settings on openSUSE

vim and sudo vim use different settings on openSUSE… here is a solution to the problem.

vim and sudo vim use different settings on openSUSE

I

want vim to save the collapsed code after I close the file. I’ve added the following code to /etc/vimrc and ~/.vimrc:

au BufWinLeave ?* mkview
au BufWinEnter ?* silent loadview

When I open the file (vim file) as a normal user, it works as expected. If I open with a sudo vim file instead, it doesn’t save the folding code.

I know /etc/vimrc is being read. My theme is set at the bottom of that file and works fine. I had a similar issue last week when installing the vim surround plugin. When it is installed in ~/.vim, it only works with vim files. In order for it to work with sudo, I had to install it separately in /usr/share/vim/current. What could be the cause?

Solution

Preamble

In fact, you’ve already answered your question, so it’s really the same question you’ve had before. This is caused by the algorithm that Vim uses to find its configuration (see: help initialization). But I wouldn’t call your solution the right one. See: Help $VIM to learn how to use your configuration (for example, becoming root) in the sudo environment.

About your current question.

See the following references in the documentation. :Help:mkview:

:mkvie[w][!] [file] ...
        When [file] is omitted or is a number from 1 to 9, a
        name is generated and 'viewdir' prepended.
                    ...

and :help 'viewdir':

 'viewdir' 'vdir'   string (default for ... for Unix: "~/.vim/view", ...

So after sudo, all Views are stored by Vim in /root/.vim.

Solution

Let viewdir point to your ~/.vim/view directory, which has the following in /root/.vimrc:

:set viewdir=/home/user/.vim/view

However, there are some problems with this approach itself:

  1. Updating a root-saved View results in a permission error.
  2. You will not be able to pass a stored View for a file under /root or /home/user because the file name generated by Vim has a tilde instead of the full path. <

The first problem can be solved by running chown or chmod on a new View file immediately after executing the :mkview command. It should look like this:

execute '!chown user:group' eval('&viewdir').' /'.substitute(expand('%:p:~'), '/', '+=', 'g').' ='

But I don’t know of any good solution to the second problem, I can only suggest writing a script to convert the filename to the full path.

Related Problems and Solutions