Skip to content

Commit 1651828

Browse files
committed
do workaround on replacing entire buffer not to move the cursor on undo (issue #8)
Replace current buffer with workaround not to move the cursor on undo (issue #8) The points are: - Do not touch the first line. - Use :put (p, P and :put! is not available). To meet above condition: - Delete all lines except for the first line. - Put formatted text except for the first line.
1 parent cd4e2e4 commit 1651828

File tree

1 file changed

+28
-2
lines changed

1 file changed

+28
-2
lines changed

autoload/clang_format.vim

+28-2
Original file line numberDiff line numberDiff line change
@@ -165,8 +165,34 @@ function! clang_format#replace(line1, line2)
165165
let formatted = clang_format#format(a:line1, a:line2)
166166

167167
if s:success(formatted)
168-
call setreg('g', formatted, 'v')
169-
silent keepjumps normal! ggVG"gp
168+
try
169+
" Note:
170+
" Replace current buffer with workaround not to move
171+
" the cursor on undo (issue #8)
172+
"
173+
" The points are:
174+
" - Do not touch the first line.
175+
" - Use :put (p, P and :put! is not available).
176+
"
177+
" To meet above condition:
178+
" - Delete all lines except for the first line.
179+
" - Put formatted text except for the first line.
180+
"
181+
let i = stridx(formatted, "\n")
182+
if i == -1 || getline(1) !=# formatted[:i-1]
183+
throw "fallback"
184+
endif
185+
186+
call setreg('g', formatted[i+1:], 'V')
187+
undojoin | normal! 2gg"_dG
188+
put g
189+
catch
190+
" Fallback:
191+
" The previous way. It lets the cursor move to the first line
192+
" on undo.
193+
call setreg('g', formatted, 'V')
194+
normal! ggVG"gp
195+
endtry
170196
else
171197
call s:error_message(formatted)
172198
endif

0 commit comments

Comments
 (0)