Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I think that the only problem with your script is that the position saving doesn't seem correct. You can essentially do what you are trying to do with:</p> <pre><code>:s/\s*\%#\s*/ /e </code></pre> <p>which is identical to the (correct) code in your question. You could simply map this with:</p> <pre><code>:nmap &lt;space&gt; :s/\s*\%#\s*/ /e&lt;CR&gt; </code></pre> <p>If you want to save the position, it gets a little more complicated. Probably the best bet is to use something like this:</p> <pre><code>function! JustOneSpace() " Get the current contents of the current line let current_line = getline(".") " Get the current cursor position let cursor_position = getpos(".") " Generate a match using the column number of the current cursor position let matchRE = '\(\s*\)\%' . cursor_position[2] . 'c\s*' " Find the number of spaces that precede the cursor let isolate_preceding_spacesRE = '^.\{-}' . matchRE . '.*$' let preceding_spaces = substitute(current_line, isolate_preceding_spacesRE, '\1', "") " Modify the line by replacing with one space let modified_line = substitute(current_line, matchRE, " ", "") " Modify the cursor position to handle the change in string length let cursor_position[2] -= len(preceding_spaces) - 1 " Set the line in the window call setline(".", modified_line) " Reset the cursor position call setpos(".", cursor_position) endfunction </code></pre> <p>Most of that is comments, but the key thing is that you look at the length of the line before and after the substitution and decide on the new cursor position accordingly. You could do this with your method by comparing <code>len(getline("."))</code> before and after if you prefer.</p> <p><b>Edit</b></p> <p>If you want the cursor to end after the space character, modify the line:</p> <pre><code> let cursor_position[2] -= len(current_line) - len(modified_line) </code></pre> <p>such that it looks like this:</p> <pre><code> let cursor_position[2] -= (len(current_line) - len(modified_line)) - 1 </code></pre> <p><b>Edit (2)</b></p> <p>I've changed the script above to consider your comments such that the cursor position is only adjusted by the number of spaces before the cursor position. This is done by creating a second regular expression that extracts the spaces preceding the cursor (and nothing else) from the line and then adjusting the cursor position by the number of spaces.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload