3

This feature is one of the concerns while editing others projects, editors like textmate and sublime I believe add line break for last line, but when I edit end portions of a file with vim and save it I sometimes forget to add the final line break.

So, how do I automate this and make sure files always have at least one new line at the end.

2
  • Hmm, I've tested vim and, if open a file and force its writing, last newline is always added. Do you have specific options which prevent vim against this fix? Commented Jan 5, 2014 at 8:57
  • @Netch I've checked .vimrc I do not have any such options, I'd like to know how to explicitly tell VIM to add new lines at the end. Commented Jan 5, 2014 at 9:46

1 Answer 1

5

I don't remember if there is solution for this build in vim. Check below snippet. It will add empty line at the end of file.

function! AddLastLine()
    if getline('$') !~ "^$"
        call append(line('$'), '')
    endif
endfunction

autocmd BufWritePre * call AddLastLine()
Sign up to request clarification or add additional context in comments.

2 Comments

Works perfect! out of curiosity. the last line autocmd BufWritePre * call AddLastLine() means when saving all kinds of files right? how to customize this further to work only on/excluding specific filetypes. Thanks a ton.
Use autocmd BufWritePre *.c\|*.cpp\|*.java\|*.py call AddLastLine() but it will works only for specified extensions, you want filetypes so the better way is this autocmd FileType c,cpp,java,python autocmd BufWritePre * call AddLastLine().

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.