Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Vim add spaces when joining lines?

I want to unwrap text in Vim. When I join lines I get an additional space between sentences.

Why is that?

like image 218
binOr Avatar asked Oct 16 '09 16:10

binOr


People also ask

How do I join lines in Vim?

When you want to merge two lines into one, position the cursor anywhere on the first line, and press J to join the two lines. J joins the line the cursor is on with the line below. Repeat the last command ( J ) with the . to join the next line with the current line.


2 Answers

I have a feeling this is what you really want: gJ

From :h gJ:

gJ          Join [count] lines, with a minimum of two lines.             Don't insert or remove any spaces.  {not in Vi} 

This is handy if you've copied something from a terminal and it's pasted it as a big rectangular block into vim, rather than a single line.

I usually use it in visual mode. Hilight stuff, gJ.

like image 99
overthink Avatar answered Oct 05 '22 00:10

overthink


Formatting destroys information. There are many different blocks of text which will result in the same one once formatted. Therefore, there's no way to reverse the operation without prior knowledge (i.e. undo).

Unformatted:

Unformatted text could start out as either all one line, or several, yet look the same when formatted.  Unformatted text could start out as either all one line, or several,  yet look the same when formatted. 

Formatted:

Unformatted text could start out as  either all one line, or several,  yet look the same when formatted. 

If you want your paragraph all on one line, or if you're okay with a little manual fiddling, you can use J to join lines back together. You can use visual mode to apply the J command to several lines at once, perhaps combined with ap or ip to select a paragraph, e.g. vipJ. Again, you'll still lose some information - multiple spaces at line breaks before formatting will end up collapsed to single spaces. (You can actually join without modifying spaces by using gJ instead of J, but you'll already have lost them when you formatted)

If you're bothered by the extra spaces after sentences (lines ending in !, ?, or .), turn off joinspaces: set nojoinspaces

like image 22
Cascabel Avatar answered Oct 05 '22 01:10

Cascabel