Question: Sometimes I accidentally leave blank lines at the end of the file I am editing.  

How can I trim them on saving in Vim?

### Update

Thanks guys, all solutions seem to work.  

Unfortunately, they all reset current cursor position, so I wrote the following function.

```
function TrimEndLines()
    let save_cursor = getpos(".")
    silent! %s#\($\n\s*\)\+\%$##
    call setpos('.', save_cursor)
endfunction

autocmd BufWritePre *.py call TrimEndLines()

```

Answer: 
You can put this into your vimrc

```
au BufWritePre *.txt $put _ | $;?\(^\s*$\)\@!?+1,$d

```

(replace `*.txt` with whatever globbing pattern you want)

Detail:

* `BufWritePre` is the event before writing a buffer to a file.
* `$put _` appends a blank line at file end (from the always-empty register)
* `|` chains Ex commands
* `$;?\(^\s*$\)\@!?` goes to end of file (`$`) then (`;`) looks up backwards (`?…?`) for the first line which is not entirely blank (`\(^\s*$\)\@!`), also see `:help /\@!` for negative assertions in vim searches.
* `×××+1,$` forms a range from line ×××+1 till the last line
* `d` deletes the line range.
Inspired by solution from @Prince Goulash, add the following to your `~/.vimrc` to remove trailing blank lines for every save for Ruby and Python files: 

```
autocmd FileType ruby,python autocmd BufWritePre <buffer> :%s/\($\n\s*\)\+\%$//e

```