sponsor Vim development Vim logo Vim Book Ad

intermediate Tip #1497: convert between C /* */ comments and C++ // comments

 tip karma   Rating 88/37, Viewed by 7999 

Read and edit this tip on the Vim tip wiki. The wiki may have a more recent version of this tip.

created:   January 31, 2007 16:14      complexity:   intermediate
author:   Paul Ivanov      as of Vim:   5.7

I'm using a stubborn ansi C compiler and found having to do old /* */ C-style comments annoying, especially if i wanted to add a short little two word comment. (WARNING: this does not deal with multi-line /* */ comments)

So now I just write // C++ style comments, and hit use \c to convert them to C style comments before compilation, and \C to convert them back to C++ after compilation (easier on the eyes, \ is my leader)

put this in your .vimrc:
"c++ // to c /* */ comments
map <leader>c  :%s/\/\/\(.*\)/\/*\1\*\//<CR>/
                                                                                                                                        
"c /* */ to c++ // comments (WARNING: this does not deal with multi-line /* */ comments)
map <leader>C :%s/\/\*/\/\//<cr>:%s/\*\///<cr>

alternatively, you can make commands out of these regular expressions:
command! CtoCpp :%s/\/\/\(.*\)/\/*\1\*\//<CR>/
command! CpptoC :%s/\/\*/\/\//<cr>:%s/\*\///<cr>

 rate this tip  Life Changing Helpful Unfulfilling 

<< replace ^M characters from MSWindows file | Delete words in a different way. (For Unix Admins) >>

Additional Notes

info at bertram dash scharpf dot de, February 1, 2007 3:53
The patterns become slightly more readable when
you use another delimiter than / and \v:

%s:\v//(.*):/*\1 */:
%s://\(.*\):/*\1 */:

Remove /* and */ at once. Avoid trailing spaces.

%s:/\*\(.\{-\}\)\s*\*/://\1:
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 the maillist. Help Bram help Uganda.
   
SourceForge.net Logo