encoree1337
encoree1337

Reputation: 337

.vimrc configuration file does not load when editing with 'sudo'

I have problem with .vimrc file, the problem is that it sometimes get loaded, and sometimes not.

  1 set number
  2 syntax on
  3 set autoindent
  4 map <F2> :!g++ % -Wall -time -O<CR>
  5 echo "it works!"

I've added echo to check if it's loaded, and when I type e.g. vim .vimrc, it gets loaded and shows me "it works" in terminal, but when I type e.g. sudo vim test.cpp it doesn't get loaded, the message doesn't show up. I'm using debian.

Upvotes: 8

Views: 9746

Answers (5)

ChrisZZ
ChrisZZ

Reputation: 2141

sudo vim /etc/sudoers

change this line:

Defaults env_reset

to:

Defaults !env_reset

and re-login your shell

Upvotes: 0

eloyesp
eloyesp

Reputation: 3275

You can use the -E flag to keep your environment variables, so vim can find your vim config.

-E, --preserve-env

Indicates to the security policy that the user wishes to preserve their existing environment variables. The security policy may return an error if the user does not have permission to preserve the environment.

Use it like:

sudo -E vim /path/to/file

But be warned that it is less secure than sudoedit as you would be trusting your vim config (and all the plugins) with root access.

Upvotes: 1

Christoph M&#246;bius
Christoph M&#246;bius

Reputation: 1402

I want to use vim on an AWS EC2 Amazon AMI instance.

Neither of the above answers helped me to get the color scheme or the plugins working with sudo. The solution that got it working, however, is to be found here:

In your .profile, .bashrc or the like add:

EDITOR=vim
VISUAL=$EDITOR
export EDITOR VISUAL

and then edit the file using sudoedit /path/to/file.

Upvotes: 0

Ingo Karkat
Ingo Karkat

Reputation: 172510

When you use sudo, Vim gets launched under a different user (root). As this user has a different home directory, another ~/.vimrc is loaded (or none, if that user doesn't have one). You can solve the problem in multiple ways:

  1. You can directly specify the location of your .vimrc: sudo vim -u $HOME/.vimrc (this won't help with plugins, though).
  2. You can use sudo -e <file> or sudoedit.
  3. You can symlink your .vimrc (and the .vim plugins directory) for root: sudo ln -s $HOME/.vimrc .vimrc; sudo ln -s $HOME/.vim .vim
  4. You can change the entire home directory of root to be the same as yours (not recommended, because of security and access rights!)

Upvotes: 16

FDinoff
FDinoff

Reputation: 31419

sudo vim causes vim to be run as the root user. Which mean vim looks for the the vimrc in root's home directory and not yours.

The two choices you have to fix this are use

sudo -e <file>

Or copy your vim configuration to root's home directory.

sudo -e or sudoedit copies the file to a tmp directory and allows you to edit it and then copies it back on save. This is safer than using sudo vim and is the recommended way of solving this problem.

Upvotes: 2

Related Questions