Pages

Vi editor tips for programmers-1

A series of posts describing tips  helpful for programmers  who use VI editor. 


Finding matching braces in a program

The common error that comes across during programming in any language is mismatching braces. vi gives an easy way to track the matching
brace for each closing or opening brace.

For eg:

**********test.c**************

#include<stdio.h> 
main ()
{
printf("Hello world"); 


***************************
Open a vi editor and type the above program (or any program) into it and save it as test.c.

Move the cursor to the closing brace } and hit the % key. The cursur will auotmatically move to the corresponding openging brace .

Now try this one

*******************test.c******************
#include<stdio.h> 
main ()
{
printf("Hello world")); 

******************************************

In the above program we have added an extra closing ")" bracket for the printf function call. Move the cursor to the second closing bracket and
hit "%". You will notice that the cursor does not move any where as it does not find the matching closing brace.

Let us look at one more example with a few more braces

******************test.c**********************
#include<stdio.h>
main ()
{
printf("Hello world");  
if(1) {
        printf("Hello again");
        }
else {
        printf("Hello once more");
        }
        }



************************************************

Let us start by matching the opening brace this time. Move the cursor to first curly brace "{" and press "%". The cursor will move  to the closing brace "}" just above the final closing brace, which makes it obvious that one brace is extra in the code, thus we can remove the final curly brace to correct the program.

In the next post we will look at a few tips related to line numbers in the "vi" editor.
~

No comments:

Post a Comment