0

I think of writing as saving, and quitting as committing. Recently I discovered "undofile" which while wonderful breaks my save/quit mental model. I'd like for ":undo" with "undofile" to behave exactly like "u" without "undofile". For example, I don't want to undo more than my intent, then ":wq".

I started by adding this to my vimrc file, but because ":undo" continues past save points, the behavior is significantly different:

nnoremap <expr> u &modified ? "u" : ""
nnoremap U u

With some advice I was able to build an autocmd group, but I can't find a combination of events that mimics the loading and unloading of buffers. "BufRead" triggers on undesired events - for example on ":e". "BufNew", "BufAdd", and "BufCreate" don't trigger on desired events - for example when opening existing files, leaving "b:myvar" undefined.

augroup histsep
    autocmd!
    autocmd BufRead * :let b:myvar = undotree()["seq_cur"] | :echom b:myvar
augroup END

nnoremap <expr> u undotree()["seq_cur"] != b:myvar ? "u" : ""
nnoremap U u

I'm looking for an autocmd that only triggers when the vim's undo history would be cleared - when a buffer is loaded or unloaded.

edit:

Right now I have this, which though very inefficient (triggers every buffer focus) certainly seems to work. I'd love any suggestions and improvements. I'm not familiar enough with the minutia of Vim to claim this is an equivalent ":undo" - do any Vim gurus care to chip in?

function HistSepSet()
    if exists("b:histsep_var")
        return
    endif
    let b:histsep_var = undotree()["seq_cur"]
endfunction

function HistSepCall()
    let l:seq_cur = undotree()["seq_cur"]
    if l:seq_cur != b:histsep_var
        return "u"
    elseif l:seq_cur == 0
        echomsg "Already at oldest change"
        return ""
    else
        echomsg "Already at oldest change for the current session"
        return ""
    endif
endfunction

augroup histsep
    autocmd!
    autocmd BufEnter * call HistSepSet()
augroup END

nnoremap <expr> u HistSepCall()
nnoremap U u

edit v2:

I've used asciinema to record a gif of the code above in action.

asciinema-gif of the above code in action

1
  • 1
    I don't understand your question. What is it you're trying to achieve? Can you edit and show an example with actual and expected behavior? If you don't want to use the undofile option, then :set noundofile and you're set.
    – Friedrich
    Apr 2 at 10:16

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.