sponsor Vim development Vim logo Vim Book Ad

basic Tip #639: Comment highlight #ifdef DEBUG for code-read ease (C/C++)

 tip karma   Rating 8/8, Viewed by 1102 

created:   January 20, 2004 1:11      complexity:   basic
author:   Karthick Gururaj      as of Vim:   6.0

Hi all,

If your C/C++ code is scattered with statements like
#ifdef DEBUG
   // Some code..
   cout << "Debug output: blah" << endl;
#endif

and you would like to highlight these segments in a different colour (so that
you can skip them visually), add the following code in your .vimrc (colouring
follows that of comments)

CODE STARTS
syn region MySkip contained start="^\s*#\s*\(if\>\|ifdef\>\|ifndef\>\)" skip="\\$" end="^\s*#\s*endif\>" contains=MySkip

let g:CommentDefines = ""

hi link MyCommentOut2 MyCommentOut
hi link MySkip MyCommentOut
hi link MyCommentOut Comment

map <silent> ,a :call AddCommentDefine()<CR>
map <silent> ,x :call ClearCommentDefine()<CR>

function! AddCommentDefine()
   let g:CommentDefines = "\\(" . expand("<cword>") . "\\)"
   syn clear MyCommentOut
   syn clear MyCommentOut2
   exe 'syn region MyCommentOut start="^\s*#\s*ifdef\s\+' . g:CommentDefines . '\>" end=".\|$" contains=MyCommentOut2'
   exe 'syn region MyCommentOut2 contained start="' . g:CommentDefines . '" end="^\s*#\s*\(endif\>\|else\>\|elif\>\)" contains=MySkip'
endfunction

function! ClearCommentDefine()
   let g:ClearCommentDefine = ""
   syn clear MyCommentOut
   syn clear MyCommentOut2
endfunction

CODE ENDS

To see the effect, position the cursor on the word DEBUG in the C code snippet above and type ,a

 rate this tip  Life Changing Helpful Unfulfilling 

<<Editing ActiveState Perl batch files | See your vim templates in Windows Explorer's New context menu >>

Additional Notes

If you have questions or remarks about this site, visit the vimonline development pages. Please use this site responsibly.
Questions about Vim should go to [email protected] after searching the archive. Help Bram help Uganda.
    stats
Sponsored by Web Concept Group Inc. SourceForge.net Logo