vim: Join all lines in paragraph

Just found this answer

:set tw=1000000
gggqG

Which is the absolute winner IMHO.

It executes gq on the motion from gg (start) to G (end of document), using a textwidth of 1000000.


Click: Pragmatic approach added

much underrated command mode and :global

Update Fixed after a correct comment. It happened with whitespace-only lines containing Tab-character(s)... sry bout that.

:g#\v[^\s\t]#normal vipJ

How does that work for you? (perhaps replacing vipJ -> vipgJ if you like)

Update Here is one that not uses normal mode (inspired by Peter's comment)

The big benefit is that it reuses the same pattern in negative and positive sense; That way it can be genericized to

:let @/='\v^\s*$'
:v//.,//-1 join

Now the second line shows the simplicity of the this approach (for every nonmatching line, join up until the next matching line). The best thing is that you can use any odd search pattern instead

Of course you could write this particular task as one line, but it wouldn't quite be as elegant:

:v#\v^\s*$#.,//-1 join

Replace all newlines followed by something other than a newline with the second matched character:

:%s/\(\S\)\n\(\S\)/\1 \2/

Another approach:

:%s/\n\([^\n]\)/\1/

Tags:

Vim

Line