Search code examples
vimvi

.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.


Solution

  • 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!)