Reputation: 34907
Say I had the following text
word1 word2 word3 word4
and the cursor was somewhere between word2
and word3
.
word2
and word3
with a single space in Vim?:s/ */ /g
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
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
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
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
Reputation: 107
I would do this in two steps
Upvotes: 0
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
Reputation: 71939
ciw
and then escape back to normal mode, although it will only work if you're on a space.
Upvotes: 29
Reputation: 142911
Try replacing all double spaces (repeated zero or more times) with a single space.
:s/ \+/ /g
Upvotes: 11