2016-08-30 - By Robert Elder
The .viminfo File Is Created As Root
Updated 2016-12-11: Made a correction to ownership changing command to make it work on a larger range of systems.
The first time you use vim, the file '~/.viminfo' is created, and if you use 'sudo vim' the first time you use vim after installing it on a fresh system, the permissions on ~/.viminfo will have the owner set to root instead of the default user.
That's a problem, because when vim is started as a normal user it can't write to this file, and every time you close vim it forgets:
- The last thing in the copy/paste buffer
- The last search term
- Any of your recent regexes
- Lots of other stuff
If you're a vim power-user you are probably used to pressing 'up' to get your last regex, or any other hard to type ex command:
Or you probably enjoy being able to open a file and press 'n' to jump directly do whatever you searched for last. Instead you now get 'E35: No previous regular expression.':
Run this command:
sudo chown $(id -nu):$(id -ng) ~/.viminfo
When you use 'sudo', the current user changes, but the value of $HOME does not. Since $HOME doesn't change '~' expands to '/home/user' instead of '/root', and root's .viminfo gets created at '/home/user/.viminfo'. If you did 'sudo -i vim', then it would go to '/root/.viminfo' instead because the '-i' flag on sudo also changes the $HOME environment variable to be '/root'.
I felt this was worth sharing because it took me quite a while to figure this problem out. It's the kind of thing that doesn't show up well if you Google for the symptoms, and I originally assumed it must have been related to different vim versions and just put up with it. It wasn't until I did a bit more digging that I realized it was so easily fixable all this time!
Use Vim Inside A Unix Pipe Like Sed Or AWK
Subscribe to Updates
XKCD's StackSort Implemented In A Vim Regex
|@RobertElderSoft On Twitter|