Robin van der Vleuten

How to use Vim on Linux and macOS

If you have ever tried to edit files on Linux through the terminal, you have probably run into Vim. It is a text editor that ships with macOS and many Linux distributions.

It is handy, but confusing the first time you open it by accident. Exiting Vim is still one of the most viewed questions on Stack Overflow for a reason.

Here are the few commands you need to open a file, make a change, and exit again.

How to open a file

Use vim or vi with the name of the file you want to open. If the file does not exist in the current directory, Vim creates it.

bash
vi file-to-open.txt

How to edit a file

When a file opens, Vim starts in normal mode. You can read the contents and run commands, but typing will not insert text yet. Press i to enter insert mode. In insert mode, your keystrokes change the text. Press <ESC> to return to normal mode.

Other Vim commands start with : and can only be entered from normal mode.

A good overview is provided by the following reference diagram.

An overview of all available Vim modes
Source: https://github.com/nilp0inter/Vim-for-Muggles

How to exit Vim

When you are done, press <ESC> to make sure you are in normal mode. Then use :q or one of its siblings:

vim
:q - just quit when you don't have any changes
:q! - quit and discard any changes you've made
:wq - quit and save all changes to the file