Climbing the Almighty Vim Ladder


Search and Replace Visually

When you need to search for and replace in only part of a file:

  1. visually select the block
  2. type :
    • vim inserts ‘<,’> to denote your selection
  3. search as usual by typing s/oldword/newword/g
    • ‘g’ ensures all occurrence, not just the first are changed

To search without visually selecting:

:%s/dog/cat/g
  • appending c, prompts for confirmation before replacing

The Power of Global Commands

Syntax:

:[range]g/<pattern>/command

How do you use this? Say you’d like to delete all blank lines…

:g/^$/d

Or simply display all line with Joe or Fred:

:g/joe.fred/

Or to yank all lines with the word “fred” alter command to y A

Delete everything in between:

:g/<pattern1>/,/<pattern2>/d

Add or delete on many lines, at once!

Say you’re working with:

2012: 5.68,
2013: 6.02,
2014: 6.38,

To surround all the dates with quotes:

  1. visually select
  2. type I (or A) (must be capital)
  3. then type “ (or any word you desire)
  4. escape

et voila:

"2012": 5.68,
"2013": 6.02,
"2014": 6.38,

Tags, Parenthesis, and all that

With Tim Pope’s Surround Plugin

<div>hi there</div>

becomes

<p>hi there</p>

through cst<p>. In English:”change surrounding tag to <p>”

Similarly, cs(“ changes () to “”

To surround a word with a <span> tag: ysiw<span>

And best of all, for an entire line, select visually then S to surround with tag of choice.

Pasting

If you paste while in insert mode, Vim will paste poorly formatted text: poor_format_java

There are two solutions:

  1. If you brew install Vim (7.4+), use the unnamed register: ”+ p will properly paste from the system’s clipboard.

  2. Use paste mode

    • :set paste
    • paste in insert mode
    • :set nopaste (to exit pastemode)

You then get nicely formatted code: nice_format

Small Goodies

  • gv reselects last visual area
  • g; jump to last edit
  • s deletes character and activates insert mode