I always wondered why vim didn't have the
just-one-space function. It's one of the most useful functions
that is available during coding.
So today I tried to write one myself, the newsgroups and searchengines didn't come up with something good. First of course it is a good idea to understand the effect of this operation. The just-one-space function removes all whitespace around the cursor and replaces it with one space character.
How can this be done in vim. The replacement part isn't that hard. It can be
done with one
:s///, something like:
:s/\s+/ /. This
will of course remove whitespace from the wrong place, at the start of the
The missing piece in this substitution is of course the place of the cursor. So
I started looking for it. Most help text about the substitution operator can be
:s helppage (
:help :s). But there is no
mentioning of the first part of the substitution. The description of the
vim regexp engine can be found at the regexp help page (
This contains a description of all the possible meta characters that can be
matched. So I the meta character that will match at the cursor position
\%#). This solved the second part of the problem.
This will remove the whitespace surrounding the cursor. The only only problem that still isn't solved is the problem that the cursors moves to the beginning of the line. It would be better if it stays at the same or a the end of line if there is not enough room to go to the last position. Probably the best place to put the cursor is on the first character after the inserted space. I may have to look into that a little more.
The function is finished by adding the
e flag at the end of the
substitution. With the
e flags the
:s will be silent
when the first part of the substitution doesn't match.
I bound the function to the spacebar in normal mode with the following command:
:nmap <space> :s/\s\+\%#\s\+/ /e
I will try this for some time and look how it works, could be good or better.