Saturday, December 31, 2011

Re: folding ruby comments

josh, Sat 2011-12-31 @ 04:31:03-0800:
> the problem is it's folding 2 lines whenever there is only 1 comment.
>
> def self.perform(picture_id)
> #do something that takes time
> puts "doing some job. picture id #{picture_id}"
> sleep(5)
> puts "done!!!"
> end

If I understand you correctly, Vim is folding the first 2 lines inside
the body of the function you gave as an example.

This is exactly what your foldexpr is telling it to do. It says, "Fold
any line that contains a hash character, optionally preceded by
whitespace". Both the comment line and the `puts` line meet this
criterion. It's not folding an extra line after the comment line, it's
folding 2 separate lines that each individually match the foldexpr you
gave.

In the case of the `puts`, the hash does not indicate the start of a
comment. But Vim doesn't know that, it's just doing what you told it to
do. You need to make your regex "smarter", so that it will match hashes
that begin a comment, but not hashes that begin a variable interpolation
within a string.

Perhaps something like this would work:

let &foldexpr = getline(v:lnum) =~ '\s*#[^{]'

(I used `:let-&` instead of `:set` just because it allows more liberal
use of unescaped spaces.)

But the above would still match a string that contained a literal hash
character that was not part of a variable interpolation, such as

"My phone # is 555-2345."

Perhaps you should count the quotation marks to determine whether the
hash character occurs inside of a string literal to deal with this case.
I'm not a Ruby programmer, so the precise details of the syntax are a
little fuzzy to me; I'll leave this and other corner cases as an
exercise for you to figure out. :)

No comments: