The basics of using Vim to edit text on a server
If you’ve opened vi or vim by mistake and don’t know how to exit vim, this guide is for you.
Vim is a powerful text editor, based on and using a lot of the same commands as the older editor Vi. Because of how efficient Vim is when it comes to navigating and editing text files, many programmers use it as their main editor when coding. However, it has a bit of a bad reputation among newer users due to its steep learning curve. If you’ve never used it, even exiting the program can be a daunting task.
To open a file in Vim, navigate to it in your terminal and type vim followed by the filename:
$ vim testfile
If there is no file with that name in your current directory, Vim will create it whenever you save it.
Vim is based on editing in different modes. When you start it, it’s in normal mode, which is used for navigation, or running commands. You can always go back from other modes to the normal mode by pressing Esc. Navigating in normal mode can be done with the arrow keys, or HJKL, respectively left, down, up, right.
The other mode primarily used is called Insert mode. In insert mode, Vim acts like any normal editor: You can type with the alphanumeric keys, and navigate with the arrow keys. Once you’ve removed or added your changes, press Esc to go back to Normal mode.
To save the file, you have to be in normal mode and run a command. The normal command for saving is:
:w
w stands for write. It has to be lower-case.
To exit vim, use q:
:q
If you have any unsaved changes to the file, vim won’t let you exit with q. Either run wq:
:wq
to save and exit, or run q!:
:q!
to force exiting without saving.
Vim is a very advanced and powerful editor. There is a lot available to learn if you want to get more proficient in vim than your regular text editor, but these few basics we’ve explained here should help you survive if you ever end up on a machine that only has vi or vim installed, which is quite common in the sysadmin world.