Monday, March 30, 2009

Vim usefull commands

The other day my colleague asked how to reach to the start of the function in vim editor. For few seconds I could not recollect. How do I do it !!!!!!!. I know it, I use it regularly, but just could not recollect how.
So I thought lets write it down whenever I find some thing useful about vim editor.



1. How to reach start of a function
'{' x2
i.e successively press curly brace ({) twice


2. How to reach start/end of code block enclosed between braces/brackets
shift +5 i.e press ' %'


3. How to enable code folding based on syntax of the programing language used
:set foldmethod=syntax
will fold the code
zo - will open a folded code
zc - will fold a open code
You can set the level folding by
:set foldlevel=1
the depth at which folding to start



4. How to enable line number
:set nu

5. How to hide a buffer
:hide
6. How to see the open files present in buffer
:buffer


7. How to select a particular buffer file from the list of files listed from the above command
:buff num i.e say the file you are interested in is at position 7, then
:buff 7

8. How to split your display window
:sp
or
:vs
i.e 'sp' will split the view horizontally and 'vs' will split the view vertically

9. To change between different views
ctl+w arrowkey
i.e to change to view area above your current view then, hold ctl key press w then press up arrow key.


10. The most frequently used command is search
/searchstring


11. If you want to search and replace
:%s/search/replace/gc
i.e search is your string to search and replace is the string with which to replace. The 'g' at the end indicates that the search and replace is to be applied on all occurence on that line.
The 'c' at the end will ask for confirmation to replace for every occurrence of the search string. If you do not want to be prompted for confirmation then do not use 'c'.
% indicates to apply it on the entire file.
If you want to search and replace on some section of the file then

:30,60s/search/replace/g
The above command will replace all occurrence of "search" in lines 30 to 60 and replace all occurrence with "replace"


12. Some times you might find that your terminal gets froze or lock when you unknowingly press ctls+s for saving data.
ctl+q
i.e if your terminal view got locked or frozen then press ctl+q to come out of the sleep.



13. vimdiff:
Jumping to diffs
[c
jump backward to previous diff

]c
Jump forward to next diff

Resolving the difference
do
Get the other buffer contents to the current buffer to resolve the difference

dp
Put the current buffer contents to the other buffer to resolve the difference




14. indent the entire file
reach to top of the file
= shift+g (i.e  press "=" and them shift +g)
15.indent the block of document
visual select the block ctl+v
=


There are many more such useful commands available,
the best way to find them out is to google it or :help

Followers