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.
I found the previous answers using substitute caused trouble when operating on very large files and polluted my registers. Here's a function I came up with which performs better for me, and avoids polluting registers:

```
" Strip trailing empty newlines
function TrimTrailingLines()
  let lastLine = line('$')
  let lastNonblankLine = prevnonblank(lastLine)
  if lastLine > 0 && lastNonblankLine != lastLine
    silent! execute lastNonblankLine + 1 . ',$delete _'
  endif
endfunction

autocmd BufWritePre <buffer> call TrimTrailingLines()

```