Pages

VI editor tips for programmers -2

Playing around with line numbers

In the last post, VI editor tips for programmers -1 , we saw how VI editor helps in keeping track of the braces in a program.
In this post let us look at a few tips that relate to line numbers in a program.

Very often a compilation error points out to a line where some thing is wrong for eg :

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


If we compile the above program using gcc compiler as follows

$ cc hello.c

We get the error

test.c: In function ‘main’:
test.c:6: error: expected ‘;’ before ‘)’ token
test.c:6: error: expected statement before ‘)’ token

The error thrown also speciifes the line number in which there is possible error. From the above error we know there might be an error in the line no 6.

Now open the file using vi

$ vi test.c 


To go to the sixth line we could either move with the arrow keys looking at the bottom right of the editor for  the line numbers being displayed.
But if the code is too big and error is 100th or the 1000th line then just using arrow keys of pgup, pgdwn keys are not convienient.
To move to any line number in the file directly , go to command mode (by pressing esc)  and type

:"number" 

That is in our case, to go to the 6th line we will have to type

:6 

and press enter. The cursor should automaticlly move to the sixth line.


Another way of doing this is to pass the line number while opening the file itself .

$ vi test.c +6  

The file opens with the cursor directly placed at the sixth line.

Moving with in the file by specific number of lines can also be done with out using the arrow keys.
To move two lines above/before the current line just do the following in the command mode

:-2  

To move by two lines below/after the current line

:+2 

Hope the tips makes programming and debugging much easier.

No comments:

Post a Comment