Vim – Useful commands

I’m learning new commands in VIM all the time, but I’m sure everyone learns something new once in a while. I’ll post here most of Vim useful commands as i’m discovering them. You can contribute to this, just by posting a comment. As simple as that! :)

One thing that’s really annoying and happens to me every time, is that i forgot to sudo before vim and after making lots of changes, I discover that the file is not writable. Pretty mood changing.

It usually goes like this. You open a file and you forget to use sudo:

You make many changes and then you type:

And you get an error:

“/etc/apache/httpd.conf” E212: Can’t open file for writing
Press ENTER or type command to continue

And then you go like, duh. At this point you either quit vim:

And open the file again with sudo:

And make all the changes again.
Or if you’re a bit smarter, you save the file to /tmp directory:

And then you sudo move the /tmp/foo to the right location:

 

Don’t do that anymore!

Use this command:

 

This command will save you hundreds of hours throughout your career. Here’s how it works – vim spawns sudo tee FILENAME and pipes the contents of the file to its stdin. The tee command now runs in a privileged environment and redirects its stdin to FILENAME. The >/dev/null discards tee’s stdout as you don’t need to see it.

In fact, don’t use this command as it’s too too long and complicated to remember! Save another few hundred hours and create a vim alias for this command because you’ll use it for the rest of your life. Put this in your ~/.vimrc:

Now the next time you’re in this situation, just type:

Cheers!