rxin en route

vim customization series #2: search within a function/block

leave a comment »

Normally, “/” searches through the whole file. Often I would like to search for the occurrence of a particular variable within a block of code or within a function.

To do that, put the following into .vimrc file:

" reference: http://vim.wikia.com/wiki/Search_keywords_in_c_function
" Search within top-level block for word at cursor.
nnoremap <Leader>[ "ayiw/<C-R>=ScopeSearch("[[")<CR><C-R>a<CR>
" Search within current block for word at cursor.
nnoremap <Leader>{ "ayiw/<C-R>=ScopeSearch("[{")<CR><C-R>a<CR>
" Search within current top-level block for user-entered text.
nnoremap <Leader>/ /<C-R>=ScopeSearch("[[")<CR>
" Return a string to place at the beginning of a search to limit
" the search to a certain scope.
" navigator is a command to jump to the beginning of the desired scope.
function! ScopeSearch(navigator)
 exec 'normal ' . a:navigator
 let l:s = line(".")
 normal %
 let l:e = line(".")
 normal %
 if l:s < l:e
 return '\%>' . (l:s-1) . 'l\%<' . (l:e+1) . 'l'
 endif
 echo "Cannot find search scope with command " . a:navigator . " %"
 return ""
endfunction

What the code does is when you press “\” followed by a “/”, it executes this function to calculate the beginning and end of the current function, and generates the command to do a search within those lines.

This is obtained from http://vim.wikia.com/wiki/Search_keywords_in_c_function

Advertisement

Written by rxin

October 23, 2009 at 2:29 pm

Posted in Productivity

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.