0

My current solution to automatically load & save views of a file is the following:

" automatically saves & loads folds when closing or opening a file
set viewoptions-=options
augroup remember_folds
    autocmd!
    autocmd BufWinLeave *.* mkview
    autocmd BufWinEnter *.* silent! loadview
augroup END

The only problem with this is it is saving views of vim help files I open (with no folds/edits in the help file). Anyone know how to write something along the lines of:

# if file opened is a vim help file:
#    don't save view
# else
#    save view

?

4
  • 1
    Welcome to Vi and Vim! I think something like this should work: autocmd BufWinLeave * if &ft !=# 'help' | mkview | endif and then similarly to restore it autocmd BufWinEnter * if &ft !=# 'help' | silent! loadview | endif. Note I used just * instead of *.* for the pattern... Unless you really don't want to match files that don't have an extension anywhere, which I think is unlikely... Would you mind trying these two above and seeing if they work for you? Thanks!
    – filbranden
    Jan 10 at 3:05
  • 1
    I dont have references offhand, but this kind of autocommand does seem to cause lots of trouble when folks forget about it and then they cant get folds/options/whatever to do what they want bc the autocommand keeps restoring old versions. Consider using sessions instead
    – D. Ben Knoble
    Jan 10 at 15:15
  • 1
    @filbranden that seems to do the trick, thanks! The reason I do the *.*. instead of of * is because using the * will save a view of terminal windows. Probably not a huge issues, but I imagine the view directory could get kind of out of hand. Jan 10 at 20:33
  • @Ben I recall seeing issues with this but it was mostly due to restoring options, so set viewoptions-=options should take care of that for the most part. Not sure what you mean about sessions, since :mksession actually creates a script that will restore views, so isn't that essentially the same? (See step 9 in help of :mksession.)
    – filbranden
    Jan 10 at 21:21
1

You can have your autocmds check what the &filetype is when making a decision. For something as short as checking that it's different from 'help' you might be able to go with a one-liner (use | to separate commands), for something more complex go with a separate :function (to help keep your sanity!)

For your specific case:

set viewoptions-=options
augroup remember_folds
    autocmd!
    autocmd BufWinLeave *.* if &ft !=# 'help' | mkview | endif
    autocmd BufWinEnter *.* if &ft !=# 'help' | silent! loadview | endif
augroup END

You mentioned using *.* as a pattern instead of * to avoid matching terminal buffers. That's also something you could potentially check inside an if statement, for example checking for &buftype !=# 'terminal'.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.