3 回答

TA貢獻(xiàn)1776條經(jīng)驗 獲得超12個贊
我認(rèn)為這幾乎就在那里,完成了你的要求,但我看到它正在刪除一個撤消點(我認(rèn)為這是預(yù)期的undojoin):
function! GoFmt()
try
exe "undojoin"
exe "Fmt"
catch
endtry
endfunction
au FileType go au BufWritePre <buffer> call GoFmt()
編輯
根據(jù) MattyW 的回答,我想起了另一個選擇:
au FileType go au BufWritePre <buffer> %!gofmt
:%!<some command>在緩沖區(qū)上執(zhí)行一個 shell 命令,所以我在將它寫入文件之前執(zhí)行它。而且,它會將光標(biāo)放在文件頂部......

TA貢獻(xiàn)1843條經(jīng)驗 獲得超7個贊
這是我的做法。它似乎在讀/寫 autocmds 和綁定到一個鍵上都運行良好。它將光標(biāo)放回并且不包括撤消中的文件頂部事件。
function! GoFormatBuffer()
if &modifiable == 1
let l:curw=winsaveview()
let l:tmpname=tempname()
call writefile(getline(1,'$'), l:tmpname)
call system("gofmt " . l:tmpname ." > /dev/null 2>&1")
if v:shell_error == 0
try | silent undojoin | catch | endtry
silent %!gofmt -tabwidth=4
endif
call delete(l:tmpname)
call winrestview(l:curw)
endif
endfunction
我檢查可修改,因為我使用 vim 作為我的尋呼機(jī)。

TA貢獻(xiàn)1943條經(jīng)驗 獲得超7個贊
我試圖使用@pepper_chino 的答案,但遇到了一些問題,如果 fmt 錯誤,那么 vim 會在運行之前撤消最后一次更改GoFmt。我以一種漫長而稍微復(fù)雜的方式解決了這個問題:
" Fmt calls 'go fmt' to convert the file to go's format standards. This being
" run often makes the undo buffer long and difficult to use. This function
" wraps the Fmt function causing it to join the format with the last action.
" This has to have a try/catch since you can't undojoin if the previous
" command was itself an undo.
function! GoFmt()
" Save cursor/view info.
let view = winsaveview()
" Check if Fmt will succeed or not. If it will fail run again to populate location window. If it succeeds then we call it with an undojoin.
" Copy the file to a temp file and attempt to run gofmt on it
let TempFile = tempname()
let SaveModified = &modified
exe 'w ' . TempFile
let &modified = SaveModified
silent exe '! ' . g:gofmt_command . ' ' . TempFile
call delete(TempFile)
if v:shell_error
" Execute Fmt to populate the location window
silent Fmt
else
" Now that we know Fmt will succeed we can now run Fmt with its undo
" joined to the previous edit in the current buffer
try
silent undojoin | silent Fmt
catch
endtry
endif
" Restore the saved cursor/view info.
call winrestview(view)
endfunction
command! GoFmt call GoFmt()
- 3 回答
- 0 關(guān)注
- 277 瀏覽
添加回答
舉報