Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

vim

spacing

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.

like image 209
HANS LARSSON Avatar asked Mar 12 '26 22:03

HANS LARSSON


1 Answers

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.

like image 102
builder-7000 Avatar answered Mar 15 '26 16:03

builder-7000



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!