3

How can I cut blank lines at the end of the file in Vim?

 2 years ago
source link: https://www.codesd.com/item/how-can-i-cut-blank-lines-at-the-end-of-the-file-in-vim.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

How can I cut blank lines at the end of the file in Vim?

advertisements

Sometimes I leave blank lines in the bottom of file.
How can I trim them on saving?

UPDATE

Thanks guys, all solutions seem work.
Unfortunately, they all reset current cursor position, so I wrote this function

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

au BufWritePre *.py call TrimEndLines()


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.

Tags vim

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK