History
Article Edit this page Discussion

Search keywords in c function

From Vim Tips Wiki

Jump to: navigation, search

Tip 1530 Previous Next 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.

[edit] References

[edit] Comments

Rate this article:

Share this article:

Hubs Highlights International Sites Wikia messages
Entertainment
Gaming
Cartoons & Comics
Science Fiction
Hobbies
Sports
See all...
Grand Theft Auto
Doctor Who
Legend of Zelda Wiki
Terminator Wiki
Everquest II Wiki
Mystery Science Theater 3000
German
Spanish
Chinese
Japanese
More...
Wikia is hiring for several open positions
Send this article to a friend
"Search keywords in c function"
 
 
Hi!

I thought you'd like this page from Wikia!

http://vim.wikia.com

Come check it out!
Send confirmation