I have written this script that replaces many spaces around the cursor with one space. This however doesn't work when I use it with no spaces around the cursor. It seems to me that Vim doesn't replace on a zero-width match.
function JustOneSpace()
let save_cursor = getpos(".")
let pos = searchpos(' \+', 'bc')
s/\s*\%#\s*/ /e
let save_cursor[2] = pos[1] + 1
call setpos('.', save_cursor)
endfunction
nmap <space> :call JustOneSpace()<cr>
Here are a few examples (pipe |
is cursor):
This line
hello | world
becomes
hello |world
But this line
hello wo|rld
doesn't become
hello wo |rld
Update: By changing the function to the following it works for the examples above.
function JustOneSpace()
let save_cursor = getpos(".")
let pos = searchpos(' *', 'bc')
s/\s*\%#\s*/ /e
let save_cursor[2] = pos[1] + 1
call setpos('.', save_cursor)
endfunction
This line
hello |world
becomes
hello w|orld
The problem is that the cursors moves to the next character. It should stay in the same place.
Any pointers and or tips?