Thursday, February 25, 2010

Vim tips and tricks

Vim search "char" and replace by a line break
In order to replace the newline character by any other character one can use:
:%s/char/\t/gc
As Vim uses '\n' for a newline in patterns, but '\r' for a newline in replacement strings. Check
:help sub-replace-special

Convert Dos files to Unix files
On can remove the carriage return ( ^M ) characters with the following command:
:%s/^M//gc (to delet the carriage returns)
:%s/^M/\t/gc (to replace it by a line break)

To input the ^M character, press Ctrl-v , then press Enter or return.

Easy switch between .h and .c files
While programming in C, one need to alternate between source.c and the corresponding header source.h. Easy to do so by these commands:
:e %<.h
This command opens the corresponding header file.
:sp %<.h
This command opens the corresponding header file in a horizontal split.
:vsp %<.h
This command opens the corresponding header file in a vertical split.

Reformat in vim for a nice column layout
%!column -t

Capitalize words and regions
gu{motion} and gU{motion} commands convert a region to lower/upper case.

Replacing Tabs with spaces and back in VIM
:set noexpandtab
:%retab!


Check file type
:set ft?

Delete all empty lines
:g/^$/d

Delete all empty lines or that contain only whitespace characters
:g/^\s*$/d

Delete all trailing whitespace and condense multiple blank lines into a single blank line
:%s/\s\+$//e
:%s/\n\{3,}/\r\r/e


Avoid the escape key
Use Alt/Meta In a Terminal
:Alt+(h or j or k or l)

Jumping to previously visited locations
Press Ctrl-O to jump back to the previous (older) location.
Press Ctrl-I (same as Tab) to jump forward to the next (newer) location.
:jumps % Display the jump list for the current window