While researching how to remove C and C++ style comments from a file, I stumbled on the following two comments by Alan Mackenzie from almost 20 years ago:
I can assure you, as half of the Emacs CC Mode team (which includes full support for AWK, by the way ;-), that C Comments can be recognised without parsing the language beyond the level of comments and strings. C comments can be fully recognised by regular expressions (because, containing no unbounded nesting, they are finite-state mechanical), though those regexps are considerably more involved than one might at first expect.
The proof of the pudding is in the eating - Load a file.c into Emacs, and its comments get correctly "fontified" (syntax highlighted), no matter how cleverly you attempt to confuse it. Emacs does not contain a C compiler.
But you'd probably be better off following the suggestion of using the C preprocessor to eliminate the comments. Or maybe you could use Emacs, searching for blocks of text fontified with font-lock-comment-face, and deleting these.
and I, being a beginner Emacs user, have the same question as Ed Morton:
Also, the main point here is to strip C comments, so let us know if emacs can do that with a flag and without going into a GUI editting mode. If so, and I knew where to get the tool, I'd probably use that one tool rather than the chain of sed/gcc commands I posted elsethread.
Currently, I'm borrowing a very complex sed script to do the job, but still it fails in some very edge cases. I dismissed the C preprocessor method because doing that in a reasonably side effect free way requires GCC with support for some options that are only available in select platforms. Also, I later found out that the files I want to remove comments from also support Python style comments, and there is no way I'm modifying that IQ-200 sed script, but it seems rather easy to do in Emacs.
My question is, is there a way to strip comments of the forms /*comment*/
, //comment
and #comment
using only the command-line interface through a pipeline of Emacs scripts and Unix utilities?
//
-style and#
-style comments end at the end of the line? Are the delimiters limited to column 1 or can they start in the middle of a line? What happens if you have a//' or a
#` inside a/* ... */
comment? We could make up our own rules, but it would be better if you specified them exactly.cpp
when an unterminated multiline string is encountered (I can add the test case to the question later when I find it; emacs' syntax highlighting agrees with cpp's output so it's definitely more robust than the sed script). The/* ... */
style comments are block comments while//
and#
are line comments, just like in C and Python. I don't know how to specify them in a formal grammar, nor do I think that's useful.