At the beginning of last year I wrote a weblog entry about how to write a function that removes all space but one in Vim. It didn’t work like I wanted, but now it does.
function JustOneSpace()
" replace all whitespace around the cursor with a space
s/\s*\%#\s*/ /e
" search backwards for a space
call search(' ', 'be')
" move to the first character after the space
normal l
endfunction
nmap <space> :call JustOneSpace()<cr>
I added the call to the search()
function to move to the space that was
substituted. All this time I wanted to fix this function by using regexes or
special vim variables. I couldn’t find these. This is quite obvious, but it
didn’t come to mind at first.
Update
I looks like this function doesn’t work when it’s used on a line with no space. It will insert a space on the spot it is supposed to, but then moves the cursor to the first space it finds when searching backwards.