4
  • When i used following code to keep my folder view, it seemed that vim -R and view don't work at all (Only [readonly] was shown but it didn't work at all). Is there any misunderstanding about it?

    " save and restore view automatically                                      
    autocmd BufWinLeave * silent! mkview                                       
    autocmd BufWinEnter * silent! loadview
    
  • Thank you for all the people who can help me.

1 Answer 1

2

By default, :mkview saves the state of the 'readonly' option. This means if you previously closed the file when it wasn't read only, then when you reopen it, :loadview sets :set noreadonly and changes it back. From :h :mkview

The output of ":mkview" contains these items:
...
3. Restore mappings, abbreviations and options local to the window if
   'viewoptions' contains "options" or "localoptions".  For the options it
   restores only values that are local to the current buffer and values local
   to the window.

So changing the value of 'viewoptions' will fix this:

set viewoptions-=options

but this will also prevent :mkview from saving almost every other option. You can see what happens when you run :loadview with different values of 'viewoptions' by looking at the file that it generates - the files are in ~/.vim/view, or ~/.local/share/nvim/view on neovim, and it's just a bunch of ex commands.

If you actually want to just restore the cursor position every time then there's a much simpler method that doesn't involve writing any files, look at :h restore-cursor. The example there registers its autocmd on BufReadPost, you can easily change that to autocmd BufWinEnter

2
  • Really appreciate for your great help. But actually i used it to save my fold view. I am looking for a better way to restore it which doesn't conflicted with readonly option.
    – user17761
    Jun 9, 2018 at 5:17
  • Using set viewoptions-=options doesn't actually affect folding behaviour, you should be fine with it as long as 'viewoptions' contains fold (see :h 'viewoptions') Jun 9, 2018 at 12:18

Your Answer

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