From cf4f9538ba1a3375cde16fad0e78432bbb23eecd Mon Sep 17 00:00:00 2001 From: Kim K Date: Wed, 15 May 2019 21:49:01 +0200 Subject: [PATCH] feat: Do not delete/insert comment if nothing has changed --- autoload/doge/comment.vim | 27 +++++++++++++++++++++++++++ autoload/doge/generate.vim | 24 ++++++++++++++++++------ 2 files changed, 45 insertions(+), 6 deletions(-) create mode 100644 autoload/doge/comment.vim diff --git a/autoload/doge/comment.vim b/autoload/doge/comment.vim new file mode 100644 index 00000000..00f5ab9e --- /dev/null +++ b/autoload/doge/comment.vim @@ -0,0 +1,27 @@ +" ============================================================================== +" Filename: comment.vim +" Maintainer: Kim Koomen +" License: MIT +" ============================================================================== + +let s:save_cpo = &cpoptions +set cpoptions&vim + +function! doge#comment#has_changed(old_comment, new_comment) abort + if len(a:old_comment) != len(a:new_comment) + return 1 + endif + + for l:old_line in a:old_comment + let l:old_line_idx = index(a:old_comment, l:old_line) + let l:new_line = get(a:new_comment, l:old_line_idx) + if trim(l:old_line) !=# trim(l:new_line) + return 1 + endif + endfor + + return 0 +endfunction + +let &cpoptions = s:save_cpo +unlet s:save_cpo diff --git a/autoload/doge/generate.vim b/autoload/doge/generate.vim index 7e94c22f..da4dbba7 100644 --- a/autoload/doge/generate.vim +++ b/autoload/doge/generate.vim @@ -89,7 +89,15 @@ function! doge#generate#pattern(pattern) abort if l:has_old_comment let l:cursor_pos = getpos('.') - execute(l:old_comment_start_lnum . 'd' . l:old_comment_lines_amount) + + " Preserve the old comment before deleting. + let l:old_comment = getline(l:old_comment_start_lnum, l:old_comment_end_lnum) + let l:comment_has_changed = doge#comment#has_changed(l:old_comment, l:comment) + + " Delete the old comment. + if l:comment_has_changed + execute(l:old_comment_start_lnum . 'd' . l:old_comment_lines_amount) + endif " If we have deleted a comment that is 'below' the function expression then " our cursor moved a line too much, so revert its position. This is the @@ -112,11 +120,15 @@ function! doge#generate#pattern(pattern) abort let l:comment_lnum_inherited_indent = line('.') endif - " Write the comment. - call append( - \ l:comment_lnum_insert_position, - \ map(l:comment, {k, line -> doge#indent#line(l:comment_lnum_inherited_indent, line)}) - \ ) + " Write the comment if it changed. + if l:comment_has_changed + call append( + \ l:comment_lnum_insert_position, + \ map(l:comment, {k, line -> doge#indent#line(l:comment_lnum_inherited_indent, line)}) + \ ) + else + echo '[DoGE] Comment is up-to-date, skipping' + endif if l:has_old_comment call setpos('.', l:cursor_pos)