forrest Jiang
forrest Jiang

Reputation: 113

How to join two lines and remove unnecessary spaces in Vim

In Source Insight, when two lines are joined, the extra spaces will be shrunk. For example:

This is line one,<space><space>
<space><space>and this is line two

will be joined to:

This is line one,<space>and this is line two

But in Vim, the join command will produce:

This is line one,<space><space>and this is line two

How do I get the same result as Source Insight does?

Upvotes: 3

Views: 597

Answers (1)

sidyll
sidyll

Reputation: 59277

You can't configure that with options, unfortunately. It is hard coded that lines with trailing spaces will be detected this way. And generally trailing space is not desired. You can consider the Vim's idea to be: "if there is trailing whitespace, it might be important to preserve. Otherwise it wouldn't be there". So the next line has leading whitespace removed and joined:

hello```
`there

" When joined:
hello```there

hello```
``there

" joined:
hello```there

hello````
`there

" joined
hello````there

You could change this behaviour with a map. This would overwrite your J key to first remove trailing whitespace and then join the lines:

nnoremap J :s/\s*$//<cr>J
vnoremap J :s/\s*$//<cr>gvJ

Upvotes: 5

Related Questions