Mahesh
Mahesh

Reputation: 115

In vim, how to check the #ifdef macro I am currently inside?

I use vim/cscope/ctags to browse C source code. Many a times I find a macro is defined is twice or even more times using #ifdefs and I am looking at the definition I don't want.

So my question is, is there any shortcut in vim using which I can find out if the line I am looking at is inside a #ifdef macro ?

I can get the list of all definitions using :tselect but I am looking for some shortcut like the one (below example) I use for finding the function I am in.

" Show function name                                                               
fun! ShowFuncName()                                                                
        let lnum = line(".")                                                       
        let col = col(".")                                                         
        echohl ModeMsg                                                             
        echo getline(search("^[^ \t#/]\\{2}.*[^:]\s*$", 'bW'))                     
        echohl None                                                                
        call search("\\%" . lnum . "l" . "\\%" . col . "c")                        
endfun                                                                             
map f :call ShowFuncName() <CR>     

Thanks.

Upvotes: 2

Views: 3196

Answers (2)

han pingtian
han pingtian

Reputation: 61

We can use "ctags --excmd=number" to generate the tags file. It will produce tag location use the line number, so will fix this problem.

Upvotes: 0

sehe
sehe

Reputation: 393457

I find, in my daily usage, the following is more than enough

  • [#
  • ]#

    navigate back and forth between branches of the current #if* conditional block

  • % to cycle between the same while on one of the preprocessor directive lines of the conditional block

I sometimes find myself adding a fold addhoc:

  • [#zf%
  • zf%
  • v%%zf

I just tested it on

#ifdef BLA
    #if BLO == 1
        #include <something>
    #else
        #pragma error "oops"
    #endif
#elifdef BLU
    #include <something_else>
#endif

There is no confusion between the nested conditionals, and also not with the non-conditional directives. I also find that it doesn't depend on filetype (or, that the filetype plugin for text supports it too :))

Upvotes: 10

Related Questions