How to use Vim on Linux and macOS
- Published
If you ever did try to edit files on Linux through the terminal, you'll probably have run into Vim. It is a text-based editor pre-installed on macOS and most Linux distributions.
Very handy, but a bit difficult to grasp for first-time users. Especially when you have opened up a file in the Vim editor by accident. It all bit us developers at least once in our career. As it's apparently one of the most sought-after answers on StackOverflow.
So I've summarized a couple of basic commands that will help you open a file, do some changes and then exit Vim.
How to open a file
First, you need to open a file that you would like to edit. You can use either vim
or vi
with the name of the file you would like to open. If the file does not exists in the current directory, it will be created for you.
bash
vi file-to-open.txt
How to edit a file
When you have opened up a file, you get into normal (or master) mode. You will be able to read the contents, but you can't make any changes yet. From there, you can execute commands or switch to insert mode. Within this mode, all your keystrokes will result in changes to the text. To go back to the normal mode, you need to press the <ESC>
key.
All other Vim commands start with a :
character followed by a keyword, which you can only enter when you are in normal mode.
A good overview is provided by the following reference diagram.
How to exit Vim
When you are done making changes, you need to make sure that you are in normal mode by pressing the <ESC>
key. And then use the :q
command (or one of its siblings) to exit the editor.
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