Search code examples
vimtext-formatting

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?


Solution

  • 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