Search don't scroll - Vim tip 2 of 3

New day and a new Vim post. This time it's all about how to find what you are looking for!

Requirements:

  • You are comfortable with Vim
  • You know how to configure Vim (via .vimrc)
  • You know and have chosen a mapleader

In this post we'll look on:

  • Text search in a directory
  • Moving in a document without scrolling
  • Moving around on a line

Text search in a directory

A lot of times you would like to find an occurrence of a pattern in some files. And grep is PERFECT for that. I prefer to use GNU grep. Vim 7 has built in grep, but it's much slower than GNU Grep.

This is very simple, you basically do this on the command line:

:grep -R "wiki_filter" ~/Desktop/skeletonz_svn/

This will do a recursive search for wiki_filter in ~/Desktop/skeletonz_svn/.

You could do the same in a terminal... But in the terminal you can't visit the files in a neat way. Vim will parse the results and remember them. You can then browse them in a quickfix window.

The commands

There are some quickfix commands that you'll need to use in order to browse the grep results:

  • :cn Display the next grep finding
  • :cp Display the previous grep finding
  • :cw Open the QuickFix window to get an overview over the results

The mappings

Of course, you'll want mappings for those. Here are mine:

map <leader>n :cn<cr>
map <leader>p :cp<cr>
map <leader>c :botright cw 10<cr>

Experiment :)

Moving in a document without scrolling

The way I move in a document is by search! Mostly I am looking for something, it could be a method, a variable or some specific text.

How to search

I hope you know how to do a search, if you don't here are the two most important normal-mode keys:

  • Pressing / will do a forward search
  • Pressing ? will do a backward search

Those keys are "ok", but you can be a lot faster by having these maps:

map <space> /
map <c-space> ?

I.e. pressing SPACE in normal mode will bring me in search mode.

Options

These options are essential and should be placed in your .vimrc:

set ignorecase
set incsearch
set hlsearch

Explanation:

  • ignorecase: Case will be ignored when you search
  • incsearch: You will see results while you type (Firefox has the same feature)
  • hlsearch: Search matches are highlighted

Moving around on a line

Vim can search for you on a line. Trust me: it's very efficient and you should use this.

An example

Let's say that we are on current line and # is where the cursor is placed:

  def #checkLoginInfo(self, username, password):

Now we would like to add a new parameter called time. Here is what I would press:

  • f): To set the cursor on ).
  • i, time: To insert ", time"

Efficient, yes sir!

Normal mode keys to remember

Here are the keys to remember:

  • fCHAR: Search forward after CHAR
  • FCHAR: Search backward after CHAR
10. Aug 2006 VIM Editor
© Amir Salihefendic