aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorTom Ryder <tom@sanctum.geek.nz>2017-10-30 20:33:22 +1300
committerTom Ryder <tom@sanctum.geek.nz>2017-10-30 20:40:25 +1300
commit8513d16d685369a3b2f3eaa7f4babfd070b94670 (patch)
treea037d9ff31dff0226121ee4c1847cc8c38536001
parentAdd some comments to Vim StripTrailingWhitespace() (diff)
downloaddotfiles-8513d16d685369a3b2f3eaa7f4babfd070b94670.tar.gz
dotfiles-8513d16d685369a3b2f3eaa7f4babfd070b94670.zip
Add line deletion to StripTrailingWhitespace()
In addition to its existing functionality of removing trailing spaces from the ends of lines, this change has the function remove lines at the end of the file afterwards if they contain no non-whitespace characters, based on its observations during the line iteration. This uses the older VimL functions line() and col() in preference to the newer winsaveview() and winrestview() to restore the cursor position after the range :delete moves it, so that this will hopefully work even on older versions of Vim; that is not yet tested. I am surprised that there is no line deletion function to match e.g. getline(), setline(), but it does seem to be the case: <https://groups.google.com/d/msg/vim_use/TY9NmJXh8EU/iFjOUg68AekJ>
-rw-r--r--vim/config/whitespace.vim26
1 files changed, 26 insertions, 0 deletions
diff --git a/vim/config/whitespace.vim b/vim/config/whitespace.vim
index d44ba333..d678ae8a 100644
--- a/vim/config/whitespace.vim
+++ b/vim/config/whitespace.vim
@@ -11,6 +11,9 @@ if has('eval')
" Iterating line number
let l:li = 1
+ " Line number of last line that had non-whitespace characters on it
+ let l:lw = 0
+
" Line number of the file's last line
let l:ll = line('$')
@@ -24,9 +27,32 @@ if has('eval')
" whitespace
call setline(l:li, substitute(l:line, '\m\C\s\+$', '', 'g'))
+ " If this line has any non-whitespace characters on it, update l:lw with
+ " its index
+ if l:line =~# '\m\C\S'
+ let l:lw = l:li
+ endif
+
" Increment the line counter for the next iteration
let l:li = l:li + 1
endwhile
+
+ " If the last non-whitespace line was before the last line proper, we can
+ " delete all lines after it
+ if l:lw < l:ll
+
+ " Get the current line and column so we can return to it
+ " (Yes I know about winsaveview() and winrestview(); I want this to work
+ " even on very old versions of Vim if possible)
+ let l:lc = line('.')
+ let l:cc = col('.')
+
+ " Delete the lines, which will move the cursor
+ execute l:lw + 1.',$ delete'
+
+ " Return the cursor to the saved position
+ call cursor(l:lc, l:cc)
+ endif
endfunction
" Map \x to the function just defined