We need a file we can safely edit without breaking anything important, so we create one by typing at the command line:
ls -l /bin > learning-vim.txt
Now we can edit this file by typing:
Although you typed
vi, you will start
If for some reason it doesn’t work, you might want to add an
Vim always starts in normal or command mode.
In this mode you can easily move around in a file with the normal cursor keys, including the
Del key also works as expected.
Other keys to move around the file are
Have you noticed the difference between
Ctrl+F is the same as
What do think the
B stand for?
Many keystrokes and commands are mnemonic and this makes them easier to remember.
Move the cursor to a position halfway any line of your choice.
Now press the
x and see what happens.
After that press
X and see the difference.
Note that the first one is a lowercase x and the second one is an uppercase X.
Del-key as well and see that
Del does the same as the lowercase
Now we can start to enter text.
To enter text we need to go into the insert mode.
There are many ways to enter the insert mode, but let’s start with the two basic ones.
i, type some text and leave the insert mode by pressing
You have seen that pressing the
i enters the insert mode at the position where the cursor is.
When back in normal mode move the cursor somewhere else and press
o, type some text and again leave the insert mode by pressing
As you must have noticed, a new line under the cursor was opened to type your text.
Have you tried to use the cursor keys while you were in insert mode?
Did you know that
Ctrl+Right often works as well?
To do operations like saving the file and closing vim, you have to be in normal mode.
If you are not sure, you can safely press
Esc to make sure you are in normal mode.
To save the current file and stay in vim, type
To close without saving the file, type
To save the current file and leave vim, type
:x. You can also use
ZZ, or type
The result of these three commands is the same.
Note that there is no
Are you sure? question, so be careful.
Now that you know the basics of editing with vim, let’s look at some other edit commands.
Deleting text with the
x command works fine for a few characters, but in a lot of situations it is not efficient.
d command exists and it always works with 2 characters:
dd will delete the current line and
dw will delete the current word.
Similar to the
d command is the
c command, but after deleting the stuff it will put vim in edit mode and thus act as a replace or change command.
cc you can change the current line and with
cw you change the current word.
Know that you have to press
Esc to leave the edit mode and you can change one word in a complete block of text if you like.
As mentioned before, vim has some very powerful options.
Almost any command in vim can be prefixed with a number.
You just learned the
To change the next 3 words you can use
Now see what happens when you type