From 1cbe9057efb5f9e820d9971e3810b6c3caf1bf43 Mon Sep 17 00:00:00 2001 From: Jerome Reybert Date: Sat, 18 Dec 2021 22:48:19 +0100 Subject: [PATCH] Add option to trim last empty line This new feature fixes a behavior difference between vim-clang-format and clang-format. If the 'to be formatted' buffer ends with one or several empty lines, vim-clang-format keeps one final empty line. clang-format does not let any empty line. If the 'to be formatted' buffer ends with a non empty line, both vim-clang-format and clang-format produce the same result, a code finishing with the non empty line. This problem seems to have been a problem for other clang plugin, in other editors, eg in VisualCode: https://stackoverflow.com/questions/55374304/add-a-single-empty-line-as-the-last-line-in-the-code-clang-format The culprit in vim-clang-format is the `split()` function: as the `formatted` string ends with a newline, it generates a List with a last empty item. --- autoload/clang_format.vim | 4 ++++ doc/clang-format.txt | 10 +++++++++- 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/autoload/clang_format.vim b/autoload/clang_format.vim index f4ff380..652a728 100644 --- a/autoload/clang_format.vim +++ b/autoload/clang_format.vim @@ -200,6 +200,7 @@ let g:clang_format#filetype_style_options = s:getg('clang_format#filetype_style_ let g:clang_format#detect_style_file = s:getg('clang_format#detect_style_file', 1) let g:clang_format#enable_fallback_style = s:getg('clang_format#enable_fallback_style', 1) +let g:clang_format#trim_last_empty_line = s:getg('clang_format#trim_last_empty_line', 0) let g:clang_format#auto_format = s:getg('clang_format#auto_format', 0) let g:clang_format#auto_format_git_diff = s:getg('clang_format#auto_format_git_diff', 0) @@ -260,6 +261,9 @@ function! clang_format#replace_ranges(ranges, ...) abort endif let winview = winsaveview() + if g:clang_format#trim_last_empty_line + let formatted = trim(formatted, "\n", 2) + endif let splitted = split(formatted, '\n', 1) silent! undojoin diff --git a/doc/clang-format.txt b/doc/clang-format.txt index eb3b6b3..b13ec63 100644 --- a/doc/clang-format.txt +++ b/doc/clang-format.txt @@ -240,7 +240,15 @@ g:clang_format#enable_fallback_style *g:clang_format#enable_fallback_style* ".clang-format" is not found. The default value is 1. - +g:clang_format#trim_last_empty_line *g:clang_format#trim_last_empty_line* + + If the initial buffer ends with one or more empty lines, vim-clang-format + will let one single empty line. This is not the clang-format behavior, + which do not let any empty line at the end of the file. + When the value is 1, vim-clang-format ensures that formatted buffer does + end with any empty lines. + The default value is 0 (which is the historical vim-clang-format + behavior). ============================================================================== SETUP EXAMPLE *vim-clang-format-setup-example*