How to remove all C and C++ comments in vi?
//
/*
*/
Use ctrl-V to do a block selection and then hit I followed by //[ESC] . Then you just shift-V , select the range, and type // (or whatever you bind it to).
Using the up and down arrow key, highlight the lines you wish to comment out. Once you have the lines selected, press the SHIFT + I keys to enter insert mode. Enter your command symbol, for example, # sign, and press the ESC key. Vim will comment out all the highlighted lines.
' A function removeString(vector<string>&source) takes a source code as an input and returns the code after removing its comments. A Boolean variable comment is initialized as false, which will check whether the particular block of string or character is a comment or not.
You can't. Parsing C and C++ comments is not something that regular expressions can do. It might work for simple cases, but you never know if the result leaves you with a corrupted source file. E.g. what happens to this:
printf ("//\n");
The proper way is to use an external tool able to parse C. For example some compilers may have an option to strip comments.
Writing a comment stripper is also a basic exercise in lex and yacc programming.
See also this question: Remove comments from C/C++ code
With regular expressions, because of the complexity of C/C++ syntax, you will at best achieve a solution that is 90% correct. Better let the right tool (a compiler) do the job.
Fortunately, Vim integrates nicely with external tools. Based on this answer, you can do:
:%! gcc -fpreprocessed -dD -E "%" 2>/dev/null
Caveats:
gcc
Esc:%s/\/\///
Esc:%s/\/\*//
Esc:%s/\*\///
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With