Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In vim, how to remove all the C and C++ comments?

Tags:

c

comments

vim

How to remove all C and C++ comments in vi?

//

/*       
 */
like image 218
Chiakey Avatar asked Apr 04 '14 09:04

Chiakey


People also ask

How do I comment out code in vim C?

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).

How do you comment multiple lines in vim C++?

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.

How do you turn off comments in CPP?

' 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.


Video Answer


3 Answers

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

like image 76
Jens Avatar answered Oct 14 '22 00:10

Jens


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:

  • requires gcc
  • it also slightly modifies the formatting (shrunk indent etc.)
like image 4
Ingo Karkat Avatar answered Oct 14 '22 00:10

Ingo Karkat


Esc:%s/\/\///

Esc:%s/\/\*//

Esc:%s/\*\///
like image 1
Hema Avatar answered Oct 14 '22 00:10

Hema