koturnの日記

普通の人です.ブログ上のコードはコピペ自由です.

VimでUndo履歴を消去する

:help clear-undo を見ると,

let old_undolevels = &undolevels
set undolevels=-1
exe "normal a \<BS>\<Esc>"
let &undolevels = old_undolevels
unlet old_undolevels

とすれば,undo履歴が消去できるとのこと. しかし,コマンド normal は,マッピングを展開するので, normal! を用いた方がよい. また,オプション undolevels の値を一時的とはいえ,グローバルに変更する必要は無いので,以下のようにした方がより望ましいだろう.

let old_undolevels = &l:undolevels
setlocal undolevels=-1
execute "normal! a \<BS>\<Esc>"
let &l:undolevels = old_undolevels
unlet old_undolevels

これをコマンド化し,

function! s:clear_undo() abort
  let old_undolevels = &undolevels
  setlocal undolevels=-1
  execute "normal! a \<BS>\<Esc>"
  let &l:undolevels = old_undolevels
endfunction
command! -bar ClearUndo  call s:clear_undo()

とするのも良いだろう. (Undo履歴を消したいというのはかなりレアなケースだと思うが)