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: 
This substitute command should do it:

```
:%s#\($\n\s*\)\+\%$##

```

Note that this removes all trailing lines that contain only whitespace. To remove only truly "empty" lines, remove the `\s*` from the above command.

**EDIT**

Explanation:

* `\(` ..... Start a match group
* `$\n` ... Match a new line (end-of-line character followed by a carriage return).
* `\s*` ... Allow any amount of whitespace on this new line
* `\)` ..... End the match group
* `\+` ..... Allow any number of occurrences of this group (one or more).
* `\%$` ... Match the end of the file

Thus the regex matches any number of adjacent lines containing only whitespace, terminated only by the end of the file. The substitute command then replaces the match with a null string.
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.