5

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.

Community
  • 1
  • 1
haff
  • 918
  • 2
  • 9
  • 20

2 Answers2

6

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./ /
Fabricator
  • 12,722
  • 2
  • 27
  • 40
  • I think this is really close. `Line1. Line2. Line3.` all appear on the same line appropriately, as does `Line4. Line5.`, but the blank line between the two has been collapsed. – haff May 17 '16 at 19:02
  • Subsequently, I guess I could add a blank line after each line break? – haff May 17 '16 at 19:03
  • @haff, i missed that. i guess you can use negative look ahead here, but the regex gets a little complicated – Fabricator May 17 '16 at 19:22
  • We can make it a bit easier to read without the negative look-behind by using `\zs` and `\ze`. As a bonus it is also shorter. e.g. `:%s/.\+\zs\n\ze./ /` – Peter Rincker May 17 '16 at 20:57
  • @PeterRincker, wow, wasn't aware of `\zs \ze`. very useful. thanks – Fabricator May 17 '16 at 21:31
5

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:

  • Use :%!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.
  • A substitution - See @Fabricator solution for an example

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
Peter Rincker
  • 43,539
  • 9
  • 74
  • 101