Reputation: 956
Is it possible to remove single line breaks but to keep empty lines (double line breaks I guess?) in Vim? I'm using Vim's HardPencil plugin to do some word processing, and I like the hard line breaks because it makes it easier to bounce around the file. However, I need to share this information in LibreOffice Writer or Word, and hard line breaks won't work well if others edit the file. To clarify, this is what I have:
Line1.
Line2.
Line3.
Line4.
Line5.
And this is what I would like:
Line1. Line2. Line3.
Line4. Line5.
Essentially hard line breaks should be replaced with a space, and double line breaks should be preserved.
I've tried variations of :%s/\n
but can't get the double line breaks to be preserved. I've found similar questions here and here, but these are not Vim specific.
Upvotes: 5
Views: 1801
Reputation: 45117
Use gw
(or gq
) with a motion (like G
).
gwG
gw
is Vim's paragraph formatting operator which "reflows" text to the desired 'textwidth'
. You may want to temporarily set 'textwidth'
to 0
for unlimited text width (:set tw=0
).
There some other ways as well do this as well:
:%!fmt
- same idea as above but use fmt
external tool and a filter.:v/^$/,//-j
- squeezes non-empty lines together. Fails if the end of the range does not have a blank line:g/\v(.+\zs\n)+/,-//j
- Also squeezes non-empty lines together, but avoids the range error of the previous method.For more help see:
:h gw
:h operator
:h 'tw'
:h filter
:h :range!
:h :range
:h :v
:h :j
:h :g
:h magic
:h /\zs
Upvotes: 5
Reputation: 12772
You can replace line+line break
with just line
, and use negative look ahead \(\n\)\@!
to make sure it's not followed by an empty line:
:%s/\(.\+\)\n\(\n\)\@!/\1 /
@Peter_Rincker's cleaner solution:
:%s/.\+\zs\n\ze./ /
Upvotes: 6