Search code examples
vimline

vim: Join all lines in paragraph


I'm trying without success to join all lines in a paragraph (block of text) using a vimscript.
I want to do this for every paragraph (block of text) and want to keep the empty lines between them.
(I don't want to use macros)

When I use the }w command to go to the first word in the next paragraph I noted that it does not recognize empty lines with spaces or multiple empty lines between paragraphs. That's not what I want.

So I tried this:
do a search:
\(^.*\S\+.*\n\)\{2,}
do:
normal vipgJ
do above search again etc.

It works fine when I do it manually, but I can't put this in a script.

I tried this:

 function! <SID>JoinParagraphs()   
   let i = 1   
   normal gg   
   while i <= 200   
   call search("\\(^.*\\S\\+.*\\n\\)\\{2,})", "")   
   normal vipgJ   
    let i=i+1   
   endwhile   
  endfunction

Doesn't work...
I tried also to change the line call search... for
let @/ = "\\(^.*\\S\\+.*\\n\\)\\{2,})" but that does a Join of all lines together (doesn't keep the empty lines).

What did I do wrong?


Solution

  • 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/