tpope / vim-commentary

commentary.vim: comment stuff out
http://www.vim.org/scripts/script.php?script_id=3695
5.88k stars 215 forks source link

C block comments handled incorrectly if delimiters not followed/preceded by space #29

Open wilywampa opened 10 years ago

wilywampa commented 10 years ago

Hi,

I noticed that the plugin doesn't play well with a style of comments I have to work with. This C code:

/*-----------
|  comment
|-----------*/
foo();

is commented as:

/* /*----------- */
/* |  comment */
/* |-----------*/ */
/* foo(); */

which, as you can see, causes a syntax error at the end of the comment block. The problem occurs if there is any character other than a space after the left delimiter or before the right delimiter.

I was able to make it work without a syntax error (Vim highlights it as a syntax error but it compiles) by removing the spaces from the delimiters that are added in in s:surroundings() and changing the strlen check from 2 to 1. The result is functional but ugly due to lack of whitespace and Vim's syntax error:

/*/1*-----------*/
/*|  comment*/
/*|-----------*1/*/
/*foo();*/

My suggestion is that the pre-existing '/*' and '*/' should be replaced with ' /1* ' and ' *1/ ' i.e. add spaces around the modified delimiter, but I haven't figured out a way to implement it yet.

tpope commented 10 years ago

See 8647be48ce155f6bd2c728a5e1ff05b314167972 for the initial /1* implementation, which might give some clues how to proceed.

wilywampa commented 10 years ago

I got it working, but I won't do a pull request for now because I added too many lines (20). First, I had to do multiple substitutes because I don't think I can use submatches other than submatch(0) for searches with multiple branches. Second, I could probably do something clever with the uncomment flag to handle including spaces in the substitutes or not instead of adding another if statement.

8d30a7a97e6f65bc92c498aa6acf54fbb2791428

EDIT: I realized my version adds a trailing space to the line originally containing the right-hand comment delimiter. Will fix tonight.

wilywampa commented 10 years ago

I corrected a lot of little problems that showed up in my testing and only added two more lines. It's still pretty inelegant compared to what I started with, but it handles everything I throw at it, like commenting a paragraph three levels in by including it in gggcG or gc3} and other motions, then being able to uncomment correctly back to the original including leaving trailing whitespace that was in the original text. I also regression tested it against other non-C comment styles and didn't find any problems.

b6bd945181c3ca56841263265ac9eb0f9e453027