A Beginner’s Guide to Vim
In this tutorial, I will cover the most important things that you should know about Vim in order to be comfortable with editing text files in the terminal. By the end of this article, you should have a solid understanding of how to use Vim.
This tutorial is intended for complete beginners who have not used Vim before. It might also be useful for people who only have a very basic understanding of Vim. I will assume you are familiar with basic command line concepts. No programming experience is required, but part of this tutorial will be geared towards programmers. I also assume you are using a US keyboard.
Let’s start with the basics.
Installing Vim
If you have access to a Linux terminal, Vim is probably already installed. It’s installed by default on Ubuntu and many other systems. Sometimes only “vi” is installed, so you can use that instead. It’s a much older version, but all of the basic functionality is the same.
Try running these commands in the terminal to see which command you should use:
$ type vi
vi is hashed (/usr/bin/vi)
$ type vim
vim is /usr/bin/vim
As you can see, I have both the “vi” and the “vim” commands available. On Ubuntu, use the following command with admin privileges to install vim:
$ sudo apt install vim
Now, open your home directory in a terminal and run this command.
$ cd ~/
$ vim file.txt
Exiting Vim
To exit vim without saving changes, press escape, then colon, then q, then ! (the exclamation mark character), then enter.
Vim is notorious for being so confusing at first that users don’t know how to exit it, and so it’s a commonly googled question. Give it a try, then run the command to open up vim again. Make sure to press the keys in this exact order, and do not capitalize the q character. Vim is case-sensitive.
Usually you should exit vim with escape, then colon, then q, then enter. However, if you accidentally made some edits to the file, then vim will warn you about it and fail to exit if you don’t add the exclamation mark. It will give you this message:
E37: No write since last change (add ! to override)
If you accidentally pressed some other keys and ended up in some menu, then press escape a few times if you don’t know what to do. This will usually get you back to the normal state.
Writing files
Let’s pretend that you want to save the empty file named file.txt. Because we ran vim with “file.txt” as the first and only argument, vim already knows the name of the file we’re editing. Sidenote — If you run Vim with multiple command line arguments, then you will be editing every listed file in a different mode. I don’t recommend this.
To “write” the file press escape, then colon, then w, then enter. You will see this message:
“file.txt” [New][unix] 0L, 0B written
This tells you that “file.txt” was saved, it’s a new file, it uses unix-style line endings, meaning it uses a single “\n” newline character to mark the end of each line, and the file now has 0 lines and 0 bytes.
Now if you use escape, then colon, then q, then enter, it will not give you any warning because the file does not have any unsaved changes.
Another way to save files is with “:x” instead of “:q”. So, press escape, then colon, then x, then enter. This will save the file and then exit vim. I use this one most often.
Basic editing
After opening an empty file, you should see a blinking cursor in the top left, on the first line and the first row. Press the “i” key, then type some text like “hello” and then press escape. Pressing “i” puts you in insert mode, and pressing escape takes you out of insert mode. Vim starts in this other mode, called “normal mode”. Remember that this text isn’t saved until you “write” the file as described above.
To add a new line just press enter while in insert mode. Backspace and delete will work as expected in insert mode.
Undo
The command for undoing changes in Vim is “:u”. Mistakes are bound to happen, so make sure you know how to use the undo command. Other editors use “<Ctrl>+z”, but don’t press that in Vim. On many systems this key combination will put the currently running process (Vim) in the background, and you could lose your work.
To undo an undo, you can use the command “:redo”. Keep in mind that you can’t undo or redo changes done before opening Vim, only changes from the current editing session.
Moving around
Try to write a few lines of text. Then exit editing mode. The cursor can be moved around with the h, j, k, and l keys. Remember not to press shift or any other modifier keys. Just press these four keys and see what each one does. You should discover that it moves the cursor to the left, down, up, and right respectively. After moving the cursor somewhere new, press “i” again and type something. Notice that the text is inserted where the cursor is. To be more precise, the text is inserted before the character under the cursor. Now press the “a” key and enter some text. The text will be added after the character under the cursor.
You can also use the arrow keys, if your keyboard has them. Many laptops do not, and pressing the Fn key to use the arrow keys might be more difficult than using “hjkl”.
More ways to edit
There are some other common ways to edit text. Two ways are “o” and “<Shift>+o”. When you press “o” in normal mode, it moves the cursor to the beginning of a new empty line one below where the cursor was. Likewise, when you press “<Shift>+o” in normal mode it moves the cursor to the beginning of a new empty line above where the cursor was.
Try these commands in your text file. Create a file with 10 lines. You can see the line count in the bottom right, followed by a comma and then the column number. The lines and columns are counted starting at 1.
Some other commands are “A” and “I” which are analogous to “a” and “i”, except they move the cursor to the end of the line and the beginning of the line after whitespace. These are useful for programmers. For example, using “A” you can add a comment or a missing semicolon at the end of a line, and using “I” you can comment-out the current line with something like “I//” or “I#”.
Similarly, the commands “$” and “0” move to the end of the line and the beginning of the line, but don’t change the mode. They just move the cursor. I use these very often.
There is also the “r” command, which lets you replace one character under the cursor. If your cursor is over the “c” in the word “cats” in normal mode, then when you press “rh” you change the letter to “h” so the word becomes “hats”. After this you’re back in normal mode, even without pressing escape.
Advanced moving
If you’re editing a very long text file, like a CSV file with millions of rows, then it can be very useful to jump around to any line in the file. You can do this as follows: press “:”, type a number, then press enter. The cursor will move to the line with the given number. Try this out and verify that it works by looking at the line number in the bottom right. Lines start numbered at 1, but “:0” and “:1” will both move the cursor to the first line. If the number starts with a plus or minus, then the lines moved will be relative. For example, if you’re on line 10, then use “:+4”, you will go to line 14. Or if you’re on line 50 and use “:-8” then you will go to line 42.
As a shortcut, you can jump to the last line by pressing “<Shift>+g”, similar to how “$” moves to the end of the current line. The command “gg” jumps to the first line, the same as “:0”.
Another useful way to move around is with “w” and “b”. These move one “word” forward and backward, respectively. I use this all the time to move a few words ahead when editing something. There are some special rules that determine what is considered a “word”, but it usually works as expected.
Movement commands may be preceded by “c” in order to “change” the text instead of moving the cursor. Whatever is between the cursor’s current location and where the movement command would take it gets replaced. So, “cw” removes the rest of the current word and enters insert mode, and “c$” removes the rest of the current line and enters insert mode.
Lastly, there are some movement commands that give you a shortcut to move up and down by a constant number of lines, which is useful for quickly “scrolling” through a file. These commands are “<Ctrl>+d”, “<Ctrl>+u” for moving down and up by a half page, and the commands “<Ctrl>+F” and “<Ctrl>+B” for moving down and up by a whole page. I usually use “<Ctrl>+d” and “<Ctrl>+u” to get to the general area where I need to make edits, then “j” and “k” to get to the exact line.
Searching for text and patterns
The most simple way to search for some text is to use the “/” command, type the exact text you want to search for, then press enter. The cursor will jump forward to the next occurrence of the text you searched for. Try this out in your text file. Then, press the “n” key. This will take you to the next match, if there is one. You can also press “<Shift>+n” to go to the previous match. These two commands always work. They will jump forward or backward to the last thing that you searched for, even if you made some changes in between.
The “/” command is similar to the “<Ctrl>+f” feature of other text editors. Vim also has a find-and-replace function similar to “<Ctrl>+h”. Here is an example of the command:
:%s/pasta/spaghetti/igc
This will replace all occurrences of “pasta” with “spaghetti”. But wait, what is the “/igc” at the end? Those are modifier flags. The “i” flag makes it ignore case, so it will also replace the text “PASTA” with “spaghetti”. Notice that if a sentence starts with the word “Pasta”, then this command would replace it with “spaghetti” (all lowercase). So, the “c” flag lets you confirm each instance of the text that should be replaced. You will get a prompt like this at the bottom of the screen that should be easy to follow:
replace with spaghetti (y/n/a/q/l/^E/^Y)?
Press “y” to replace the highlighted text, and press “n” to leave it unmodified and go to the next match. Press “q” or escape to cancel and go back to normal mode.
The “g” flag makes Vim perform the search globally, attempting to find every match in the current file.
For convenience, you can repeat the previous find-and-replace command by just typing “:%s” then pressing enter.
With both “/” and “:%s”, there are some special characters that won’t be interpreted literally, including “.” and “\”. Use a backslash before these special characters to interpret them literally. You can look here for a complete list of special characters.
The syntax for find and replace in Vim is very similar to the syntax of regular expressions, so if you know regular expressions, then you can use them in Vim to find and replace based on patterns instead of exact text.
There’s one more way to search for text. Using “f” and “F” you can search for a single character. Type either “f” or “F”, then type the character you want to search for. If the character occurs later in the line and you used “f”, then your cursor will move to the next occurrence of the character. “F” does the same but it goes backwards in the current line.
Highlighting, deleting, and copy-paste
Every text editor needs a way to highlight, copy, and paste. Vim is no exception.
To select or highlight some text, move to where you want to start, press “v”, then move to where you want to end using normal movement commands, like hjkl, $, G, or f.
If you want to copy the selection, use the “y” command. Then the selected text will be put in the paste buffer, all text will be deselected, and the editor will go back to normal mode. Then you can move around and use the command “P” or “p” to paste the text from the buffer, before or after the current character, respectively.
When you have something selected, both “x” and “d” will cut out the selected text and put it in the paste buffer. There’s no difference between “delete” and “cut”, except when you press the Delete or Backspace key. That actually just deletes one character. But “x” and “d” let you cut or delete lots of text at once.
For example, this sequence of commands deletes all text in the file:
:0<Enter>dG
After doing that, you could use either “p” or “:u” to put all the text back.
If nothing is selected, then “dd” will cut the current line, and “yy” will copy the current line. I use both of these commands all the time.
Repetition Repetition Repetition
The “.” command repeats the last action. If you just added the word “spaghetti” to the end of the current line, then you can press “.” to add it again as many times as you want.
When searching for something with “/”, you can make a change to the selected search result, press “n” to go to the next search result, then press “.” to repeat the same change to the current selection. Then you can alternate “n” and “.” to change all search results, or skip a single search result by pressing “n” again.
Another way to repeat things is to type a number before doing the command. This really works for almost anything. “4x” deletes four characters. “5j” moves down five lines. “3aetc. “
Note that you have to wait a moment, or press escape twice for the changes to apply.
Useful commands for programmers
The “%” command lets you jump to a matching “brace”, such as:
( ) [ ] { } < >
Just highlight a brace under the cursor, then press “%” holding shift to move the cursor to the matching brace, if there is one. In many programming languages there are often curly braces at the end of a line. You can go to a line, use “$” to go to the end of the line, then “%” to go to the matching brace.
When jumping to a matching brace, Vim ignores whitespace. It doesn’t assume that you are programming with any indentation style. Fortunately, you can use “:>” and “:<” to increase and decrease the indentation of the line, respectively. Another way to do this is with just “>” and “<”, and if you want to indent three times to the right, you could use either “>>>>>>” or “:>>>”. It’s often useful to select several lines with “y” and then use “:>” to indent them all at once.
Now is a good time to mention that vim has some configuration variables that you can change, which let you customize Vim’s behavior. The following commands could be typed in Vim and change the settings for the duration of the session, but then those changes would be lost when you close the program. So it’s best to place these settings in a dotfile named “.vimrc” in your home directory. Use the command vim ~/.vimrc to start editing this file. If this file already has stuff in it, add these lines to the end.
:set shiftwidth=2
:set tabstop=2
:set expandtab
:set smarttab
:set autoindent
Save and quit with “:x”, and then edit another file with Vim.
Excellent. Now you’re using the best settings and you never need to change them! Okay, that’s not true. You can change the variables one by one to see what they do. The variables that aren’t followed by an equals sign are boolean, and you can set them to the opposite value by putting “no” before the variable name, like this:
:set nosmarttab
:set noautoindent
shiftwidth and tabstop should both be set to the desired number of columns added by each indent. expandtab will replace the tab character with spaces.
E325: ATTENTION
Found a swap file by the name…
This is the error message you get, well, for a variety of reasons. Most often it’s because you have two or more terminals open with vim and two of them are trying to edit the same file. Vim isn’t Google Docs, so there can only be one editor at a time. When the program is running normally, it actually keeps a “swap file” right next to the file you are editing, which contains some binary information, instead of being a complete copy of the file, which would be an inefficient use of disk space. It’s basically a file representing changes made to the file since it was last saved. The important question is, what do you do if this error appears? The message appearing below the error explains everything:
(1) Another program may be editing the same file. If this is the case,
be careful not to end up with two different instances of the same
file when making changes. Quit, or continue with caution.
(2) An edit session for this file crashed.
If this is the case, use “:recover” or “vim -r asdf.txt”
to recover the changes (see “:help recovery”).
If you did this already, delete the swap file “.asdf.txt.swp”
to avoid this message.
If you think the file might be open in another editor, then just press “q” and go close the other editor or keep using it. If you are pretty sure that it’s not open in another editor, then it probably means that Vim crashed while editing the file. This can happen if you lose power or if you click the “x” button to force close the terminal instead of typing “:x” in Vim. You probably want to keep the unsaved changes you made, so press “r” to recover those changes from the swapfile and put them in the actual file. If you don’t want the edits then you can quit and delete the swap file listed in the help message with rm .asdf.txt.swp. Yours might be different.
Shortcomings
Vim is mainly a text editor, not an IDE (Integrated Development Environment).
Although you can probably accomplish 99% of your programming tasks with Vim and the command line, that doesn’t mean that it’s the best way to do those tasks.
If you’re like me, then you like being in the terminal all the time and having the ability to quickly run commands. IDEs such as VSCode have lots of features that make this possible, in addition to features missing from Vim like Git integration, smart autocomplete, autoformatting, and many more.
What next?
Vim has many powerful features, and I have found it useful even though I only know about 25% of those features. If you want to learn more …
- Try the “vimtutor” command, which is usually installed alongside Vim.
- Open the help menu with “:help”. This basically opens a window on top of the text editing window. If you want to close it right away, press escape and type “:q”. You don’t need to worry about your file getting lost, especially if you don’t add ! at the end. If you want to read the help file, you have to use vim movement commands to jump around. Try using “/” to search for stuff in the help menu. There’s a special command here — when you see a filename in the help document, you can type e.g. “:help usr_06.txt” to open that help file (there are many).
- Learn some complementary shell commands for creating, editing, and analyzing text files.
- Learn more advanced regular expressions.
- Bookmark the quick reference guide. All of the Vim help files are also on this site.
At this point, my only advice is to practice by editing some files. Have fun!