Searching and highlighting in vi editor

In this post we will look into at the ways in which we can search in a program using the VI editor.

The searching always happens in the command mode so if you want to search for a string or a pattern in the program, first step is to go to the command mode by pressing "esc"

Let us take a simple hello world program as an example.

Let us say we come across the string printf once and want to search all the occurrences of printf after the current cursor position, then just move the cursor on printf and press "*". The cursor will automatically move to the next occurrence of printf and on each press of "*" it will move to the next occurrence of printf.

To search backwards, that is behind the current cursor position place the cursor on printf and press "#". The cursor will move to the previous occurence of the search string. The second way of searching is
Go to command mode and type

any thing that follows the "/" will be taken as the search string.

Then keep pressing "n" to move to the next occurrences of the search string. If you want to move back in the document, that is search for occurrences of the string before the current cursor position use the shift "n" , i.e "N" .
To see all the matching strings at the same time we can highlight all the matched strings by setting the option hlsearch i.e.

All the items which matched the previous search string will get highlighted. To remove the highlight run the command

To make the seach case insensitive we need to set the option "ignorecase" i.e

The search can be made case insensitive by adding \c to the search string, i.e

The search can also be restrcted to specific lines. To restict the search only to a single line we need to use \%numl along with the search string. To restrict the search for strintg printf to 20th line we need to use

To restinct the search to lines after 20th line

To restinct the search to lines between 20th line and 30th lines

The same rules can be applied to columns instead of lines by replacing "l" in the command by "c".

We can also highlight patterns with color of our own wish by using the command "match". Let us say we want to highlight all the strings "printf" in red color. Then first we need to create a hightlight group by running the command

Instead of group1 we can use any group name we want, and instead of red we can use any other color name that is recognized by "vi".
Now use the command match to highlight the string printf.

group1 being the name we used while creating our group using highlight command. All the occurrences of string printf should get highlighted in red, or whatever color is chosen while running the highlight command.

To remove the highlight run the command

No comments:

Post a Comment

Follow by Email