-1

What is the quickest way to un-doublespace in Vim, without using a regex?

I.e., convert

line one
<emptyline>
line two
<emptyline>
line three

to

line one
line two
line three

There's gotta be a way without regexes, by using J somehow.

3
  • With literally three lines JjJ works (assuming the cursor starts on the first line), but that's going to get old fast. Why not %s/\n\n/\r/?
    – Telemachus
    Jan 29, 2022 at 19:55
  • @Telemachus Yeah, maybe regex isn't that much longer. Using J would seem to require a macro to do the repetitions for arbitrary number of lines.
    – Geremia
    Jan 29, 2022 at 19:58
  • @Quasímodo Yes, by double-spaced I mean lines interleaved with blank lines.
    – Geremia
    Jan 29, 2022 at 20:19

4 Answers 4

2

If you're on linux, you could call an external program to filter a range of lines (here I filter all of them with %):

:%! awk NF

In the above awk command, NF indicates the total number of fields, and hence this prints only non-blank lines, since in blank lines NF is 0 and evaluates to false.

Not sure if it's faster, but it's a different way (note this will just remove all blank lines from the document).

1

Use a recursive mapping. Define it with

:nmap <F2> gg}gJ<F2>

and then press F2. The mapping will go to the start of the file (gg), search for the next empty line (}), and try to to join the empty line with the next line, respecting leading indent (gJ). If gJ can join an empty line with the next line, the mapping will continue and call itself recursively (<F2>); otherwise it will abort.

Note that this mapping will keep all empty lines at the start of the file and will reduce two or more empty lines at the end of the file to one empty line.

1

This technically involves a regular expression, but if it's only a single blank line:

:global/./join
" aka
:g/./j
1
  • That's a shorter regex. 👍
    – Geremia
    Jan 31, 2022 at 18:33
0

Not faster than using s/\n\n/\r/, but this is a macro way of doing it:

qxJjq

Select the region you're interested in, then:

:'<,'>norm @x

to repeatedly execute macro x on it.

2
  • Defining and then calling a macro for this is not just "not faster." It's significantly more work, and for no good reason that I can see.
    – Telemachus
    Jan 29, 2022 at 20:40
  • @Telemachus Sure, but I'd like to know how the do it without a regex.
    – Geremia
    Jan 29, 2022 at 20:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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