vim tips and tricks

motivation

The more efficient you are, the less time you will spend working on your programs. Knowing some of these vim commands will cut down on your coding and debugging time.

commands

All of these are from command mode. Hit the Esc key if you are in insert mode before trying any of these.

I often use the following sequence to change all occurrences of a variable name to another name. There's a fancier way to change them all at once, but I often like to see each occurrence before I change it. In the following, I am searching for "search1" and changing it to "linearSearch":

ESC               # make sure I'm not in insert mode
/search1          # search for "search1" in my code, go to 1st occurrence
cw linearSearch   # change "search1" to "linearSearch"
ESC               # get out of insert mode
n                 # find next occurrence 
.                 # apply same cw linearSearch I just did above
n                 # find next occurrence 
.                 # apply same cw linearSearch I just did above
and so on...

tab edit

If I want to copy something from one file to another, I often use tabs in vim to open both files at the same time. Using gt you can switch back and forth between tabs, and copy/paste commands work from one file to the other (i.e., copy some lines from one file, switch tabs, then paste those lines in the other file).

Try the following with two files:

vim file1           # open one file in vim
:tabe file2         # open second file as a tab (tabe means tab edit)
yy                  # copy a line (or use 5yy to copy 5 lines, etc)
gt                  # switch tabs (gt means go to tab)
p                   # paste the line(s) you copied into this file

challenge

Try some of the above in one of your files! You can always quit without saving using :q!


CS21 Topics