Showing posts with label vim. Show all posts
Showing posts with label vim. Show all posts

Tuesday, February 14, 2012

Some Vim shortcuts

Some productivity tips:
Smart movements
* and # search for the word under the cursor forward/backward. 
w to the next word 
W to the next space-separated word 
b / e to the begin/end of the current word. (B / E for space separated only) 
gg / G jump to the begin/end of the file.
%jump to the matching { .. } or ( .. ), etc.. 
{ / } jump to next paragraph.
Quick editing commands
I insert at the begin. 
A append to end. 
o / O open a new line after/before the current. 
v / V visual mode (to select text!) 
Shift+R replace text 
C change remaining part of line.
Combining commands
Most commands accept a amount and direction, for example:
cW = change till end of word 
3cW = change 3 words 
BcW = to begin of full word, 
change full word ciW = change inner word. 
ci" = change inner between ".." 
ci( = change text between ( .. ) 
4dd = delete 4 lines 
3x = delete 3 characters. 
3s = substitute 3 characters.
Useful programmer commands
r replace one character (e.g. rd replaces the current char with d).
 ~ changes case. 
J joins two lines 
Ctrl+A / Ctrl+X increments/decrements a number.
. repeat last command (a simple macro) 
= indent line (specify a range, or use visual mode)
Macro recording
Press q[key] to start recording. 
Then hit q to stop recording. 
The macro can be played with @[key].
 
VIM as a file comparator:
Use '-d' switch to compare two files in VIM. This command splits the VIM screen vertically and shows the differences.
 
vim -d chmod-restore.pl chmod-restore1.pl
  
 

Wednesday, November 16, 2011

Saving a root owned file as normal user from within Vi/Vim

This happens lot of times. I login as a normal user and start to edit root owned file in vim / vi text editor. However, I'm not able to save changes due to permission issue (all config files are owned by root). So to save file, i can do :w !sudo tee % where
Where,
:w - Write a file.
!sudo - Call shell sudo command.
tee - The output of write (vim :w) command redirected using tee. The % is nothing but current file name i.e. /etc/apache2/conf.d/mediawiki.conf. In other words tee command is run as root and it takes standard input and write it to a file represented by %. However, this will prompt to reload file again (hit L to load changes in vim itself):