Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

vim

vi

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.

like image 420
encoree1337 Avatar asked Sep 27 '14 18:09

encoree1337


People also ask

How do I open a .vimrc file in Linux?

Vim can be configured system wide (globally) via the /etc/vim/vimrc. local file on Ubuntu/Debian based operating systems. On CentOS 7 and RHEL 7, the system wide configuration file for Vim is in /etc/vimrc. You can also do user specific configuration of Vim.

How do I edit my vimrc file?

Opening vimrc Using file name completion, you could type :e $M then press Tab until you see the desired variable. If you only want to see the path, type :echo $M then press Tab to see the variable, and press Enter. In gvim, the Edit menu includes "Startup Settings" which will use $MYVIMRC to edit your vimrc file.

What is the vimrc file?

The vimrc file contains optional runtime configuration settings to initialize Vim when it starts. On Unix based systems, the file is named .vimrc , while on Windows systems it is named _vimrc . : help vimrc. You can customize Vim by putting suitable commands in your vimrc.


2 Answers

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!)
like image 154
Ingo Karkat Avatar answered Oct 10 '22 04:10

Ingo Karkat


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.

like image 44
FDinoff Avatar answered Oct 10 '22 03:10

FDinoff