Vim Tips Wiki
Register
Advertisement
Tip 1530 Printable Monobook Previous Next

[[Vim_Tips_Wiki:New_tips{{{subpage}}}#Search in current function|created]] November 12, 2007 · complexity basic · author Anon · version 7.0


Often a programmer will want to search for something only within a certain program scope, for example, within a function. The following code provides that behavior.

" 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

With the defaults, the <Leader> key is backslash. With the mappings suggested above, you would put the cursor on a word in a C function, then press:

  • \[ to search for the word, but only within the current function.
  • \{ to search for the word, but only within the current block ({...}).
  • \/ to search for whatever text you enter, but only within the current block.

This procedure will work for any program, such as C or C++, where a code block starts with '{' and ends with '}', and where a function starts with '{' at the left margin.

References

Comments


Advertisement