HANS LARSSON
HANS LARSSON

Reputation: 125

How to join lines without adding space for empty line in Vim

When I use J to join lines spaces are automatically added as expected. However when I have a line with words followed by a blank line and I want to remove that blank line with J it adds a space to my current line. I considered nnoremaping J to Jx so that the white space is removed, but that would make it not add spaces when I am joining two lines with text in them. After looking through the manual I could not find anything that sounded like what I want.

Below are some examples of what I am looking to happen. and I am sorry in advance for the formatting.

Currently I have:

Before (spaces are replaced with - for readability):

Some-text

After:

Some-text-

Before:

Some-text
Some-more

After:

Some-text-Some-more

I desire:

Before (spaces are replaced with - for redability):

Some-text

After:

Some-text

Before:

Some-text
Some-more

After:

Some-text-Some-more

In short, I want a space when lines contain characters are joined and no space added when the line being joined is empty.

Upvotes: 3

Views: 290

Answers (1)

builder-7000
builder-7000

Reputation: 7627

You could define a function to toggle between gJ and J if the next line is empty. Then map that function to J:

noremap J :call J()<cr>
function! J()
    if getline(line('.')+1)=="" | exe 'normal gJ' | else | join | endif
endfunction

getline(line('.')+1)=="" checks if the next line is empty.

Upvotes: 4

Related Questions