Search code examples
vim

How to comment out code between two comments in C++


IF I have several code sections that looks like:

// XXX DEBUG
printf("example code");
int y = 6;
// XXX END DEBUG

I'd like to, in vim, run a command to comment out the bits between XXX DEBUG and XXX END DEBUG:

// XXX DEBUG
// printf("example code");
// int y = 6;
// XXX END DEBUG

I've tried using :g with the delimiter switched

:g#^.*// XXX DEBUG#.,#^.*// XXX END DEBUG#normal I//

But that just lands me the error message E492: Not an editor command: .,#^.*// XXX END DEBUG#normal I//


Solution

  • You can't use an alternative separator in a range. One good reason is that it is hard to know if you mean /foo/ or ?foo? when you do <whatever>foo<whatever>. Using an alternative separator in :help :g or :help :s is possible because such a confusion is not possible in that context.

    Therefore, you can keep your #s for the ":global" part but you need to either escape your // in the range for :normal:

    :g#^.*// XXX DEBUG#.,/^.*\/\/ XXX END DEBUG/normal I// <-- space here
    

    or us \v to alter the "magicness" of the pattern:

    :g#^.*// XXX DEBUG#.,/\v^.*// XXX END DEBUG/normal I// <-- space here
    

    Now, that works:

    // // XXX DEBUG
    // printf("example code");
    // int y = 6;
    // // XXX END DEBUG
    

    Hmm… kind of.

    As-is, you are prepending // to the lines between the matching lines but also to the matching lines themselves because of missing offsets:

                 here -+             and here -+
                       |                       |
                       V                       V
    :g#^.*// XXX DEBUG#.,/\v^.*// XXX END DEBUG/normal I// <-- space here
    

    In the fixed version below,

    • the range for :normal must start on the line below the matching line, so you would use .+ or simply +,
    • and it must end on the line above the search match, so you would use /re/-.

    This is how it should look:

    :g#^.*// XXX DEBUG#.+,/\v^.*// XXX END DEBUG/-normal I// <-- space here