Categories: How-To

vi command on Linux (Text Editor) [Basic Guide]

The vi Command in Linux is a powerful ASCII text editor that is widely used in the interface Linux character for editing files and programs. Its use is not very intuitive at first glance, but simple text editing can be done using few commands.

It can be especially useful for small one-off corrections, especially in a production environment. So it’s not a bad idea to know how to deal with this text editor universally available on Linux distributions.

Basically it has two working modes: the operating mode and the insertion mode. In operating mode, the vi waits for commands that will perform some action. In insert mode, everything you type is considered text.

Vi text edito

The operating mode is accessed via the ESC key. The vi always starts in this mode. To enter the insert mode, simply press the INSERT key or the “i” command.

To do simple file editing in vi:

$ vi file name

Change the insertion mode with the INSERT key or by pressing the “i” key. The cursor can be moved in this mode with the position arrows. When you finish typing press the ESC key and type:


:w to save the changes ;

:wq to save and exit vi ;

:q! to exit without saving;

Below is the table of commands accepted by vi. All commands must be given in operating mode. The “+” sign indicates keys that must be pressed simultaneously. The comma indicates that the keys must be typed in sequence. Also check out our content with all the main processes and commands in Linux.

ActionCommand
Open File:e Filename
Save File:w
Save File As:w Filename
Save and Quit:wq
Quit without save:q!
Save if content changed:ZZ
Mark a text to copy or cutv, arrow keys
To copy a marked texty
To cut a marked textc
To paste a marked textp
Copy an lineyy
Copy until end of fileyG
Delete text in front of cursor (DEL)x
delete text in back of cursor (BACKSPACE)X
Erase linedd
Erase until end of filedG
Erase until end of the lineD
Find a text below/texto
Find again/
Find a text upwards ?texto
Find again?
Undo changesu
Redo changesCTRL+r
Center the text:ce
Left align:ri
Right align:le
Open new window:new
Split window in two:split
Open file in new window:split filename
Go to window upCTRL+w, k
Go to window downCTRL+w, j
Go to beginning of line0
Go to end of line$
Go to end of the fileG
Go down one linej
Go up one linek
Go to the lefth
Go to the rightl
Go to end of screenL
Help:help
Insert text before cursori
Insert text after cursora
Insert text em uma nova linhao

Programmer Tricks with Vi

When running, I saw it searching for a configuration file called “.vimrc” in the users’ HOME directory. This file doesn’t always exist, but it can be created by the user to do some cool things with vi, such as:

Colorize the syntax

To color the syntax of files with source code, you must enable the “sintax on” directive in the .vimrc file, with the command:

$ echo 'syntax on' >> ~/.vimrc

In this way, vi will color the text, recognizing several programming languages. Use single quotes in these commands, as shown.

Syntax on in vim


Enumerate the lines

Another interesting feature in vim is line numbering, which allows you to easily debug a source code. To enable this feature, you must use the “set number” directive in the .vimrc file, with the command:

$ echo 'set number' >> ~/.vimrc

In this way, vi will list the text, making it easier to debug the code.

Enumerate the lines


Syntax Debugger

This vi option is very interesting for programmers. It allows a key to be mapped to activate a language compiler or interpreter, in order to verify the syntax, without having to leave the text editor.

In the example, the “-l” php option is used, which only performs a syntax check. The key combination chosen was CTRL B, which executes the command php -l in the source file.

$ echo 'map:! php -l%

‘>>~/.vimrc

Thus, to check the syntax of a php code, simply press CTRL B, and the php interpreter is activated to verify the syntax:

Php code with error


In this example, I induced a missing “;” error. When you press CTRL B, php will say that there is a syntax error:

Call to the interpreter


This vim facility is extremely useful in interpreted languages, which allow you to verify the syntax without having to leave the editor.

For other languages, the same concept can be used by changing the syntax check option:

PERL: echo ‘map:! perl -c%

‘>>~/.vimrc

PYTHON: echo ‘map:! python -d%

‘>>~/.vimrc

Infinite undo

The “u” key in vi’s command mode allows you to return to the previous text, undoing the changes. However, when leaving vi, the ability to undo changes is lost. So, if you’re editing a source code and exit the editor, you won’t be able to use the undo changes feature anymore.

But there is a solution for maintain a history of changes, considered a true lifesaver.

It allows vi to keep a history of file changes in a special directory on the user’s HOME.

To enable this feature, you must execute the following commands:

First, the directory is created to store the history in the user’s HOME:

$ mkdir -p ~/.vim/undodir

Then the undofile feature must be enabled:

$ echo 'set undofile' >>~/.vimrc

Finally, the directory is configured to store these files, created in the first step:

$echo 'set undodir=~/.vim/undodir' >>~/.vimrc

In this way, vi will keep the history of changes, making it possible to undo changes with the “u” key.

From time to time, it’s interesting to clear the contents of the ~/.vim/undodir directory.

Change text (replace)

The feature to replace one text with another in vim also helps a lot to make code replacements in vi.

To make a replacement, enter command mode with the ESC key and then type:

: %s/text to search for/text to be replaced/g

In this way, the vim will search for all occurrences of the text to be searched and will replace it with text to be replaced in the entire document.

If you want the vi to just replace the first occurrence, the command is the same, but without the “g” at the end:

: %s/text to search/text to replace/

If the text to be searched or replaced contains a simple “/” slash, a “\” backslash must be used first, to let the vi know that the “/” in the text is not interpreted as a separator.

In this example, the instance of “/etc” will be replaced with “/var “:

: %s/\ /etc/\ /var /g

Another interesting replacement is to place all the lines inside an HTML tag, such as a paragraph:

:s/. */

\ r&\ r/<\ /p>

The expression. * indicates the beginning of the line, and the “\ r” the “return” (end of the line).

Search text

To search for text in vi, simply press the “/” bar in command mode and type the text. In this way, the vi will search for occurrences of the search term one by one, pressing the “/” key again.

One feature to boost text searches in vi is to enable the Highlight the term, as well as enable the “case insensitive”, allowing searches ignoring whether the text is in upper or lower case:

To enable search text highlighting:

$ echo 'set hlsearch' >> ~/.vimrc

To ignore whether the term is in an upper or lower case:

$ echo 'set ignorecase' >> ~/.vimrc

To search for text in accordance with the upper box, if the term contains a capital letter:

echo 'set smartcase' >> ~/.vimrc

Indentation

An interesting trick of vi is the automatic indentation of the text.

To fix an indented source code, type in command mode:

GG=g

This way, vi will format the code, making it more readable.

It is also possible to determine that the vi indents the code while you program, varying the spacing depending on the type of source code.

To enable this feature:

$ echo 'filetype indent plugin on' >> ~/.vimrc

Then, you must create a directory called “.vim” in the HOME directory, if it doesn’t already exist:

$ mkdir ~/.vim

In this directory, a file must be created for each type of source code, as in the example:

$ cat ~/.vim/php.vim setlocal shiftwidth=2 setlocal tabstop=2

In this example, there is a php.vim file inside the ~/.vim directory.

And there are two directives in it:

  • shiftwidth=2 Determines the number of spaces for self-indentation to be 2. The default is 8 spaces.
  • tabstop=2 Determines the number of spaces the TAB contains. The default is 8 spaces.

For python for example:

$ cat ~/.vim/python.vim setlocal expandtab setlocal shiftwidth=4 setlocal softtabstop=4

In this example, the expandtab and softtabstop directives are for:

  • expandtab It doesn’t replace TAB with spaces;
  • softtabstop allows you to pretend that TABS are spaces when editing.

Remove the ^M at the end of the files

Generally after copying a text file from Windows to Linux and editing it in vi, the file appears with “^M” codes at the end of each line.

In this way, you can adjust the file in vi, using the command below, in command mode:

:e ++ff=two

The replacement command also works well:

: %s//\ r/g

Did you like it?

Share

Uirá Endy Ribeiro

Uirá Endy Ribeiro is a Software Developer and Cloud Computing Architect with a 23-year career. He has master's degrees in computer science and fifteen IT certifications and is the author of 11 books recognized in the IT world market. He is also Director at Universidade Salgado de Oliveira and Director of the Linux Professional Institute - LPI Director's Board.

Uirá Endy Ribeiro

Uirá Endy Ribeiro is a Software Developer and Cloud Computing Architect with a 23-year career. He has master's degrees in computer science and fifteen IT certifications and is the author of 11 books recognized in the IT world market. He is also Director at Universidade Salgado de Oliveira and Director of the Linux Professional Institute - LPI Director's Board.

View Comments

Share
Published by
Uirá Endy Ribeiro

Recent Posts

Sudo command on Linux (privilege scale) [Basic Guide]

The sudo command on Linux executes a given command as if it were another user.…

2 years ago

SS command on Linux (investigate the network) [Basic Guide]

The ss command on Linux is extremely useful for investigating sockets, providing various information about…

2 years ago

Free Linux command (memory usage) [Basic Guide]

Free Linux command shows the amount of total memory in use and available, as well…

2 years ago

Linux while command (loop – while) [Basic Guide]

The shell has structures for testing conditions and executing certain program sequences several times (loop),…

2 years ago

Linux fstab file (disk mount setup) [Basic Guide]

The /etc/fstab file stores the configuration of which devices should be mounted and what is…

2 years ago

Netcat command on Linux (Swiss network knife) [Basic Guide]

The Netcat Command in Linux or nc is a utility used to do “almost anything”…

2 years ago

This website uses cookies.