开发者

Vim search for class

How do I define a vim function such that when called with

Foo

it searches via vimgrep for

\s*class Foo

or

\s*struct Foo

?

[This is poorman's cscope/ctag; I want to be able to type in a class name, and have it search for the clas开发者_运维知识库s.]

If this is easy, is there a way I can tell it to look under my cursor to use that 'word' as the name to search for?

Thanks!


Here's a hack from a vim novice which seems to work:

function! SearchFunc()
  let l:filenames = substitute(glob("*.c") . glob("*.cpp") . glob("*.h"), '\n', ' ', 'g')
  try
    execute 'vimgrep /^\s*\(struct\|class\)\s*'  . expand("<cword>") . '/ ' . l:filenames
  catch
    echon 'No results found.'
    sleep 800m
  endtry
endfunction
nmap <Leader>fi :call SearchFunc()^M

This should search for the word under the cursor when you type \fi.

Explicating the code:

If you call vimgrep normally in a function and it doesn't find any results, it throws an error which looks fairly ugly, hence I wrapped it inside of a try/catch/endtry block. When an error happens, we presume it's because there was no match, and we display a message, then pause briefly so it doesn't immediately disappear.

"nmap" maps a key sequence in "normal mode" to do something. In this case, it calls the function we just defined. You have to type Ctrl-V, Ctrl-M at the end of the line to create the ^M, so it simulates you pressing return.

If you'd like to change the function to take any argument you could change it like this:

function! SearchFunc(findme)
  let l:filenames = substitute(glob("*.c") . glob("*.cpp") . glob("*.h"), '\n', ' ', 'g')
  try
    execute 'vimgrep /^\s*\(struct\|class\)\s*'  . a:findme . '/ ' . l:filenames
  catch
    echon 'No results found.'
    sleep 800m
  endtry
endfunction

Then you can call it by typing

:call SearchFunc('foo')

But it would seem easier to just use the built-in <cword> feature.


Check <cword> in :h expand() function.

fun! MySearch()
  exe 'vimgrep /\s*class '.expand('<cword>').'/ *'
endfun
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜