1. :mkexrc
The easiest way is to use :mkexrc
command. With this command, we can save all changed options into a file. When you need to restore back all the saved options from the file, just:source
it.
mkexrc snapshot
source snapshot
2. :set
and :redir
The :mkexrc
command necessarily uses a file to hold all options.(And it also saves current key mappings.) When we do not want to use any file, we can redirect output of :set
command into vim variable with :redir
.
redir => snapshot
silent set
redir END
Then, we can restore back all the options from snapshot as follows.
for opt in split(snapshot,'\n')[1:]
exe "silent set " . opt
endfor
The above approach is quick and easy to use. But the approach has two problems. First, we have to escape some characters including white spaces from the snapshot(:help option-backslash
). Otherwise we might meet errors when these characters not being escaped. For instance,
set breakat=@ !+=
raises the error 'E518' but,
set breakat=@\ \!+=
works well.
And second problem is that all the special keys are changed to normal characters when we redirect the output to snapshot. For example, ^I
(tab) is literally changed to ^
and I
. The workaround could be complicated a little bit.
let g:optionDict = {}
function SaveOpts()
redir => snapshot
" We make a snapshot of options which differ from their default value.
" If we want to make a snapshot of all options, do set all.
silent set
redir END
for opt in split(snapshot, '\W\+')
if strlen(opt) > 3
if exists('&' . opt)
exe 'let g:optionDict.'. opt . '=&' . opt
elseif opt[0:1] == 'no' && exists('&' . opt[2:])
exe 'let g:optionDict.'. opt[2:]. '=&' . opt[2:]
endif
endif
endfor
endfunc
function RestoreOpts()
for [opt, val] in items(g:optionDict)
try
exe 'silent set ' . opt . '=' . escape(val, " \t|\\\"")
catch /:E474/ " Invalid argument, do set {option} or no{option}
if val == '1'
exe 'silent set ' . opt
elseif val == '0'
exe 'silent set no' . opt
endif
endtry
endfor
endfunc
3. :setlocal
We can also save an restore option manually with :setlocal
.
:setlocal
only affects current buffer or window. If we change options with :setlocal
, :setlocal {option}<
or :set {option}<
can restore back the changed options. The former one sets the local value of {option} from its global value and the latter one remove all the local options so all the option values return to their global values. For instance,
setlocal ts=16
set ts<
:option
command and anOptionSet
autocommand event, so there might be enough interest for a "save / restore state" feature. Ask onvim_dev
.:option
command it is pretty cool! You're right maybe I'll hit vim_dev. @ Christian: Yes I get that this isn't a commom workflow, actually I'm juste trying to implement an idea of mine but maybe that's not such a good one :-)selection
have a local version? One has to read the sources to find out.)