Vim editor basics in Linux

Vim needs no presentations: it is probably the most loved text editor by system administrators, also due to the fact that it is a clone and an improvement of the original Vi, which is included by default in practically all Linux and Unix based operating systems. Vim can be quite intimidating at first, and it has a steep learning curve; learning how to use it, however, can really increase our productivity. In this article we will learn the Vim basics.

In this tutorial you will learn:

  • How to install Vim
  • Why Vim is a “modal” text editor and what are the Vim modes
  • How to tweak Vim look and feel using the ~/.vimrc configuration file

vim-logo

Software requirements and conventions used

Software Requirements and Linux Command Line Conventions
Category Requirements, Conventions or Software Version Used
System Distribution independent
Software vim
Other No other requirements needed
Conventions # – requires given linux-commands to be executed with root privileges either directly as a root user or by use of sudo command
$ – requires given linux-commands to be executed as a regular non-privileged user

Installation

You can rest assured that Vim, if not installed by default, is available in your favorite distribution repositories, therefore, to install it, all you have to do is to use your favorite package manager. On Debian and Debian-based
distributions, among the others, we can use apt-get:

$ sudo apt-get update && sudo apt-get install vim

On Fedora, and more generally on all the Red Hat family of distributions, we can use the dnf package manager to perform the task:

$ sudo dnf install vim

Running on Arch Linux? In that case, since Vim is included in the Extra repository, installing it is just a matter of running the following command:

$ sudo pacman -S vim

A “modal” text editor

You will find that vim is pretty different from the text editors you may be accustomed to; this is because it is a modal text editor. What does it mean? Vim has a bunch of different working modes:

  • Normal Mode
  • Insert Mode
  • Visual Mode
  • Command Mode

Let’s see them in brief.

Normal mode

The normal mode is the default. When in normal mode, we can easily navigate and make changes to a document. Let’s see some examples. Suppose we have the following text opened in the editor:

text-example-lotr

As you can see, the cursor is positioned at the beginning of the first line. Suppose we want to move it at the beginning of the second word (“Rings” in this case). All we have to do, is to press the w key (short for word); this will move forward (to the right) to the start of a word:

text-example-lotr


The “inverse” movement is obtained by pressing the b key – this action will move the cursor to the start of the previous word.

What if we want to repeat the movement x number of times? All we have to do is to enter the number of movements we want to perform, before pressing the key corresponding to the movement we want to make. For example, to move the cursor two words forward we would press 2w. Supposing the cursor is currently on the “Rings” word on the first line, we would obtain this result:

text-example-lotr

To move the cursor to the beginning of the current line, we can press the 0 key; the $ key will let us obtain the opposite effect, so the cursor will be moved to the end of the line.

To move to the last line of an opened document, we can press G, while to move to the first line, we can press gg.

The ones above are only a few examples of how we can easily navigate through the document when in normal mode. In the table below we can see a small number of keys we may want to remember and their effect:

KEY EFFECT
h Move the cursor left
j Move the cursor down
k Move the cursor up
l Move the cursor right
w Move forward to the start of a word
W Move forward to the start of a word (punctuation considered as part of the word)
b Move backward to the start of a word
B Move backward to the start of a word (punctuation considered as part of the word)
e Move forward to the end of a word
E Move forward to the end of a word (punctuation considered as part of the word)
0 Move to the start of the line
$ Move to the end of the line
gg Move to the first line of the document
G Move to the last line of the document
f{char} Go to the first occurrence of the specified character
A Move past the end of the line and enter “insert mode”

When in normal mode we are not limited to perform only movements, there are also operators that let us perform some actions, as, for example d (delete) or c (change). These operators, combined with motions, let us perform mass actions.

Let’s see an example: we know that the w key moves the cursor forward to the start of the next word; if we combine it with the d operator, we can delete an entire word with just one command. Supposing the cursor is at the beginning of the first line of our text, if we press dw we would obtain the following result:

text-example-lotr

As you can see, the first word of the line (“Three”) has been removed. In the same fashion we could delete text from the current cursor position to the end of the line by pressing d$, and so on.

The “Insert” (and “Replace”) mode

The insert mode is practically the standard working mode of all the most common text editors. When in this mode we can insert text like we would normally do with other editors. How do we enter this mode? When working in normal mode, we can, for example, press one of the following keys:

KEY EFFECT
i Insert text before the cursor
I Insert text at the beginning of the line
a Insert text after the cursor
A Append text at the end of a line


How to perform the inverse process, and switch from insert to normal mode? All we have to do is to press the <Esc> key or <C-[>.

The replace mode is really similar to insert mode, the only difference is that the text that we input does overwrite existing one instead of extending the length of the line. We can enter replace mode by using the R when in
normal mode.

The “Visual” mode

When in “visual” mode, we can select a portion of text and perform some operations on it. Visual mode can work at three different levels:

  • Character
  • Line
  • Block

To enter “character-wide” visual mode, when in normal mode we can press the v key; to enable “line-wise” virtual mode, instead, we can use V (uppercase). Finally, to enter “block-wise” visual mode, we can press <C-v>.

vim-visual-mode

Vim visual line

In the picture above you can see how the editor looks like, when “line-wise” visual mode is activated. The same keys we discussed above, can be used to switch between visual modes; furthermore, if we are already in a specific visual mode, and we press the key which activates it, we will switch back to normal mode:

Current visual mode Key Effect
character-wise v Switch to normal mode
character-wise V Switch to line-wise visual mode
character-wise \ Switch to block-wise visual mode
line-wise v Switch to character-wise visual mode
line-wise V Switch to normal mode
line-wise \ Switch to block-wise visual mode
block-wise v Switch to character-wise visual mode
block-wise V Switch to line-wise visual mode
block-wise \ Switch to normal mode

The movement keys we saw in normal mode, can be also used in visual mode. For example, when we are working in character-wise visual mode, and we want to select from a certain point to the first occurrence of a letter we can use
f{char}.

When a portion of text is selected, we can, for example, cut it by pressing the d keyword, or copy it by using y.

The “Command line mode”

To enter the command line mode we can press the : key or / to begin a text search when in normal mode. When we are in this mode we can enter commands to be executed after we press <CR> (the ‘return’ key). One of the simplest command we can run when in command line mode is:

:help

When the command is executed, a new buffer will be opened showing the Vim main help page:

vim-help-page

The Vim help page In recent versions of Vim, we can use the terminal command to open a terminal emulator right into the text editor:
:terminal

The result of the command execution is:

vim-terminal

The Vim embed terminal


As we already said, to perform a text search we can press / and type the text we want to find in the document. By default the search is case-sensitive (this can be modified via the Vim configuration file using the set ignorecase directive). As an example, suppose we want to find the word “Ring” in the text of our example. We write the following command by pressing “Enter”:

/Ring
vim-text-search

To cycle through the highlighted results we can press n, and to remove the highlighting of the words we can execute the noh command:

:noh

We can use command line mode also to perform text replacement. Suppose for example we want to substitute all the occurrences of “Ring” with “Jewel”. What we would do, in this case is to use the substitute command: s. The
command we would need to run is:

:%s/Ring/Jewel/g

The % symbol we used before the command makes so that the operation is performed in the whole document, while the g appended after the substitution is used to perform the substitution on all the occurrences found on a line (vs only the first one).

When we use the substitute command we can also use other “modifiers”. For example, if we append a c after the substitution pattern we will be prompted to confirm each substitution; i, instead will make the replacement case-insensitive.

The range of action of a command can be restricted to some specific lines. To perform the text replacement only on lines from the first to the sixth (inclusive) of the document, we would write:

:1,6s/Ring/Jewel/g

The same range could be used, for example, with the d (delete) command, to delete the aforementioned lines:

:1,6d

When in command line mode, we can also invoke external programs in the shell: all we have to do is to prepend such commands with the ! symbol. For example, to take a look at the (non-hidden) files in the current working directory, we could use the ls -l command:

:!ls -l

We would obtain the following result:

total 36
drwxr-xr-x. 2 egdoc egdoc 4096 Oct 31 12:45 Desktop
drwxr-xr-x. 2 egdoc egdoc 4096 Oct 31 12:45 Documents
drwxr-xr-x. 2 egdoc egdoc 4096 Nov  2 10:37 Downloads
-rw-r--r--. 1 egdoc egdoc  373 Nov  3 11:30 lotr.txt
drwxr-xr-x. 2 egdoc egdoc 4096 Oct 31 12:45 Music
drwxr-xr-x. 2 egdoc egdoc 4096 Nov  4 08:19 Pictures
drwxr-xr-x. 2 egdoc egdoc 4096 Oct 31 12:45 Public
drwxr-xr-x. 2 egdoc egdoc 4096 Oct 31 12:45 Templates
drwxr-xr-x. 2 egdoc egdoc 4096 Oct 31 12:45 Videos

Press ENTER or type command to continue

As suggested by the message, to return to the editor, we must press ENTER. These are only few, basic examples of the commands we can use in Vim.

Customizing Vim

Vim look and feel can be customized via its configuration file: ~/.vimrc. By default the editor interface is really minimal: not even line numbers are displayed! Let this be the first thing we will change.

Displaying line numbers

We open the configuration file and paste the following directive in it:

set number

Normally, to see the effect of the changes we make, we should close and re-open Vim; we can, however, also issue the :so ~/.vimrc command to source the configuration file and make the changes immediately effective. Due to the
directive we used, line numbers are now displayed:

vim-line-numbers

Highlight a column and limit line length

Another common feature we want to use, especially when writing code, is to highlight a certain column. When writing a Python program or a shell script, for example, we usually don’t want to exceed the 80 column; to highlight the column we must add the following directive into the configuration file:

set colorcolumn=80

In the image below you can see the result of the change. The column we specified is now highlighted:

vim-colorcolumn

If we actually want to enforce a rule about the maximum number of character which can be inserted on a line, we have to use the textwidth directive instead:

set textwidth=79

Due to the change above, if a new word doesn’t fit on the specified number of characters, it will be automatically inserted in a new line.

Use spaces instead of tabs

Another quite common change we may want to perform is to use a certain number of spaces in place of a TAB character when the corresponding key is pressed on the keyboard. To achieve the desired setup we want to use the following directives:

set tabstop=2
set softtabstop=2
set expandtab
set shiftwidth=2

In the above setup we set the tabstop directive to set the size of a “real” TAB character. The softtabstop, directive, instead, is used to specify the number of spaces that should be used to replace a TAB when the expandtab directive is used. In that case, each time we press the Tab key on the keyboard, Vim will insert the amount of spaces we specified with softtabstop. Finally, the shiftwidth option is used to specify the level of indentation used for auto-indenting and for shift commands.

Filetype-specific settings

What if we want to specify some settings to be applied only to specific kind of files? In that case we must activate the built-in filetype plugin. To do so, we append the following line to the configuration file:

filetype plugin on

At this point, inside the ~/.vim/after/ftplugin directory (we need to create it if it doesn’t already exist), we must create a file named after the filetype we want to specify settings for, and use the “.vim” extension.

For example, to specify settings for Python files, we would create the ~/.vim/after/ftplugin/python.vim file and put our instructions inside of it. The only thing recommended is to use the setlocal instruction in the file instead of set, in order to make the changes valid only for the opened buffer, and not global. Say for example we want to replace a TAB character with 4 spaces only in Python scripts. In the ~/.vim/after/ftplugin/python.vim file we would write:

setlocal softtabstop=4
setlocal shiftwidth=4

What we used here is only a very very small subset of the options we can use in the Vim configuration file to tweak the look and feel of the editor; what we want to show here is the basic mechanism.

Conclusions

In this article we began our first approach with what is probably the most famous and loved text editor on Linux and Unix-based platforms: Vim. We saw how Vim was created as a clone of the original Vi editor, which is installed by default on almost all distributions, we saw why it is called a modal text editor, and what are the modes we can use.

Finally, we saw how to tweak the editor look and feel by writing directives in the ~/.vimrc configuration file. We barely scratch the surface of what we can accomplish by using Vim, since this was meant as a first step guide into the Vim world. We will talk about specific features more in depth in future tutorials. Stay tuned!



Comments and Discussions
Linux Forum