mandag 19. september 2011

VIM hacks: quick tips for coding in VIM

Initial setup for a programming environment inside VIM
I prefer having line numbers and syntax highlighting in my code. to get this, you simply write :syntax on for syntax highlighting and :set nu for line numbers. Turning them off would be :syntax off and :set nu! .
both (or all, really) commands in vim can be set to automatically run when you start vim, by writing them in the /home/$USER/.vimrc file, one command each line.

Using vim for programming
Note: every command must be issued in command mode, not insert mode where you enter text. get to command mode by hitting <Esc>.
Highlighting
Hover over a parenthesis or a brace and hit % to find the matching paren or brace.
Hover over any word and hit * to highlight all words that match the current word.
Remove hightlights by typing ":nohl" (no highlight)


Search/Replace
searching is done by using the s-command, and works like this:
:<from>,<to>s/searchpattern/replacepattern/g where from and to are line numbers and the optional /g replaces all occurences on the same line if there are more than one. without /g the first occurence is replaced.

- Example unrelated to programming: 
Search patterns are powerful. By using regular expressions, the user can do all sorts of things with the search/replace function in vim. For instance, say you have a text file listing 100 mp3-files in the following format:
artist_song.mp3
You want the lines to look better, and you issue this search and replace-command:
:1,100s/\(.*\)_\(.*\).mp3/\2, by \1
and you get the result:
song, by artist

A few quick life-saving commands:
G=gg Auto-indent the whole document
:v/./d  Remove all blank lines in the document
u        undo
:!        execute external program. e.g: ":!gcc this.c"
:sh     open a shell, return to vim by pressing <Ctrl>+d


Reference:
http://www.brezeale.com/technical_notes/vim_notes.shtml

Ingen kommentarer:

Legg inn en kommentar