13

When I have automatic wrapping enabled, I can write some text like

This line is starting to get fairly long so
it has been wrapped

If I start writing a comment, I get fairly sensible behaviour:

# When I reach the maximum line width in a
# comment, the next line gets commented
# too!

If, however, I'm writing some Ruby and I'm in the middle of a string on an indented line...

str = "If I'm trying to write a ruby string, 
       and then it tries to wrap, I get a 
       surprise newline and a bunch of space!"

While this is valid Ruby code, a better way to write this would be the following:

str = "Really, what I'd like it to do is "\
      "notice that I'm in the middle of a "\
      "string and sort it out for me"

Is there a plugin or option to add special rules for wrapping certain lines, so that relevant characters can be added in a context-aware fashion?

6
  • In theory, the 'formatexpr' sounds like what you want to look at. However, when I play with it locally, it doesn't work as I'd expect it to. Instead of calling my function when textwidth is exceeded, it's doing it for every non-whitespace character typed. This could still work, but would be a big performance hit.
    – Matt Boehm
    Feb 23, 2015 at 17:16
  • 2
    @MattBoehm I think you're experiencing: "The expression is also evaluated when 'textwidth' is set and adding text beyond that limit" ... formatexpr seems the way to go to me! Feb 23, 2015 at 19:52
  • @Carpetsmoker for me, if 'textwidth' is 40, and I start typing on a new line, the expression was evaluated for every non-space keystroke, including the first letter typed. This may be due to some bug on my end. If formatexpr is working as documented for you/the asker, then it certainly seems like the solution.
    – Matt Boehm
    Feb 23, 2015 at 20:35
  • 4
    @MattBoehm You're describing what you're seeing correctly. I also interpreted the documentation as you did, so I submitted a patch to make Vim behave like it says it should.
    – jamessan
    Feb 24, 2015 at 21:54
  • 4
    @MattBoehm That patch was applied upstream as 7.4.658. :)
    – jamessan
    Mar 8, 2015 at 17:52

1 Answer 1

3

You can use a custom format expression/program to achieve what you want. Check out :help 'formatexpr' and :help 'formatprg' for info on exactly how to do this.

Note that as mentioned in the comments above, there was a bug in vim where the format expression was being called on every key inserted rather than only when the text is supposed to wrap. This has been fixed in Vim 7.4.658.

Not the answer you're looking for? Browse other questions tagged or ask your own question.