Jeromy Anglim
Jeromy Anglim

Reputation: 34907

Efficient way to remove multiple spaces between two words in Vim

Say I had the following text

 word1 word2              word3 word4

and the cursor was somewhere between word2 and word3.

Question

Initial thoughts

However, I thought there might be something quicker like diw but for spaces.

It would also be good if the strategy also worked when the cursor was on the w of word3 or the 2 or word2.

Upvotes: 33

Views: 30321

Answers (9)

Serge Stroobandt
Serge Stroobandt

Reputation: 31498

For a multi-line text

:%s/\s\+/ /g

Upvotes: 1

chipfall
chipfall

Reputation: 360

If you are editing dt<nextchar> on the second space to the right of word2 would work, in this case dtw.

Upvotes: 0

Miguel
Miguel

Reputation: 796

In 3 keystrokes, add this to your init.vim (neovim) or .vimrc (vim):

nnoremap <silent> di<Space> /<Space><Space>diwi<Space><Esc>:noh<CR>
nnoremap <silent> da<Space> /<Space><CR>diw:noh<CR>

Now, in NORMAL mode, you can "delete irrelevant space" to replace by a single space, and "delete all space" to remove all spaces.

This applies to the current or next block of spaces. Unfortunately, it cannot be repeated with the dot . operator.

Upvotes: 0

Gryglicki Łukasz
Gryglicki Łukasz

Reputation: 37

%s/\(\w\)\s\+\(\w\)/\1 \2/g
%  - global
s - search
\( - escape (
\w - (any letter, digit)
\) - escape )
\(\w\) - remember letter/digit before space as \1
\s - whitespace
\+ - escape +
\s\+ - 1 or more whitespace space
\(\w\) - remember letter/digit after space(s) as \2
/ - replcae with
\1 - remembered last letter/digit before space
' ' - space character here - single space
\2 - remembered first letter/digit after white space(s).
/ - end of replace
g - globally

Upvotes: 1

Cyrus Talladen
Cyrus Talladen

Reputation: 107

I would do this in two steps

  1. $ // cursor goes to space at the end of the line
  2. dw // deletes whitespaces ( use . to repeat as necessary)

Upvotes: 0

Seb
Seb

Reputation: 6717

I use (bound to a hotkey)

i<enter><esc>kJ

i - insert mode

k - up a line

J - join lines together

This works no matter where the cursor is inside the whitespace or on the w of word3, and puts the cursor on the beginning of the word that just got joined. If you want it to work with the 2 on word2, just replace the first i with a.

Upvotes: 2

Hank Gay
Hank Gay

Reputation: 71939

ciw and then escape back to normal mode, although it will only work if you're on a space.

Upvotes: 29

Peter Olson
Peter Olson

Reputation: 142911

Try replacing all double spaces (repeated zero or more times) with a single space.

:s/  \+/ /g

Upvotes: 11

Shad
Shad

Reputation: 15451

This works for me:

:s/\s\+/ /g

Upvotes: 36

Related Questions