I've been maintaining my own version of Strip Trailing Spaces function (attached at the bottom of this post) since I first started using vim. It grew out of a simple
:%s/\s*$// and now includes a number of features:
- it preserves search history and the last search string
- it doesn't change editor's
- it doesn't add a new jumplist and changelist record
- it preserves editor's view and cursor position
However, over the years I've noticed that I never needed to undo the results of stripping trailing spaces from a file. In fact, I would go as far as to say that when undoing changes in a file, the function produces an understandable but somewhat undesirable cursor jump (to the top-most trailing space it strippes) which disrupts my work flow. So, I set about to exclude the results of this function from the undo history all together.
After reading Restore the cursor position after undoing text change made by a script, I got an idea that I could do this by merging undo record created by the function with the previous change in the buffer (if it exists). This way, when undoing changes, it would appear that the function didn't create it's own undo record at all.
To validate my idea I've used a simple test:
set undolevels=10 normal ggiline one is bull of aaaa set undolevels=10 " used to break a change into separate undo blocks normal Goline two is full of bbbb set undolevels=10 " used to break a change into separate undo blocks normal Goline three is full of cccc set undolevels=10 " used to break a change into separate undo blocks undojoin keepjumps %s/aaaa/zzzz/ normal u
You can recreate my test by starting with a clean buffer and entering the above commands manually, or by saving the above block as a file and sourcing it via
vim +"source your-filename-here".
The test worked successfully, so I've implemented the change into my function.
Unfortunately, this is where I run into a bit of a brick wall. Merging undo record created by the function with the previous item in the undo history (via
undojoin) was trivial. However, when testing I've discovered that once the merged change is undone, the cursor jumps to the top most change in the file (which often happens to be a stripped space) and not to the position of the original change, as defined by the change list.
Can anyone think of why this would be? Better yet, can anyone suggest a fix?