Friday, September 28, 2012

Re: Changing C comments

On Friday, September 28, 2012 6:34:24 AM UTC-5, Bob von Knobloch wrote:
> Hello,
>
>
>
> I have to update many c-source programs and one important point is to
>
> change all the end-of-line comments from 'old C' (/*--*/) to C++ type
>
> (//---). This seems (to me) to be ajob that is often required but I am
>
> unable to find anything on this topic on the web. (Google is, seemingly,
>
> not my friend).
>
> Ideally, Iwould like to change the comments (only single-line ones
>
> though so /* and */ appearing on a line without their 'friend' should
>
> remain.
>
> It would also save a lot of work if there were a way to format all the
>
> new comments so that the '//' was set at a given column (or after the
>
> code if it's too long).
>
> Can anyone point me to some scripts or whatever that might help ??
>
> Sorry if this stuff is easy to find, I can't.
>

A built-in solution would be a regular expression substitute:

%s#\v/\*(%(%(\*/)@!.)*)\*/\s*$#//\1

\v - turn on "very magic"
/\* match beginning of C-style comment
(...) capture the text inside the comment as follows:
%(...)* group but don't capture, matching the following any number of times:
%(\*/)@! don't match the end of a C-style comment "*/"
. but match any other character at all
\*/ match the end of the C-style comment
\s*$ make sure the C-style comment is the last thing on the line

The replace uses //\1, which is "//" followed by the captured text (the comment content). Note this will also remove any trailing whitespace on the line.

I've used '#' instead of the traditional '/' as the pattern delimiter since '/' characters are part of the pattern and replacement text.

As requested, this works on single lines only. It might be possible to tweak it to work on multiple lines but that would probably be easier with a different method.

References:
:help /\v
:help /\@!
:help /\(
:help /\%(
...and other parts of :help pattern.txt.

If this is too complicated (regular expressions are a powerful tool but can be hard to use; "now you have two problems" and all that) then you can try out a commenting plugin. I've heard good things about "NERD Commenter", which appears to have a "switch comment style" command:

http://www.vim.org/scripts/script.php?script_id=1218

For some reason I cannot currently find any others which seem regularly maintained. I thought I remembered seeing a wide variety of them at some point.

--
You received this message from the "vim_use" maillist.
Do not top-post! Type your reply below the text you are replying to.
For more information, visit http://www.vim.org/maillist.php

No comments: