從 :h:set
我們 我知道
:se [t]
顯示與其默認值不同的所有選項。
在vimscript中,我想保存所有這些已被修改過的選項 用戶,修改它們,然後將它們恢復為用戶設置的值。
我怎麽能輕易做到這一點?
我是否有辦法簡單地將:set
(或類似命令)的結果存儲到我可以獲取的變量中,或者稍後傳遞給另一個命令以恢復它包含的內容?
或者我是否必須手動解析命令的輸出(我可以這樣做,但如果存在更簡單的替代方案,則無需任何工作)?
從 :h:set
我們 我知道
:se [t]
顯示與其默認值不同的所有選項。
在vimscript中,我想保存所有這些已被修改過的選項 用戶,修改它們,然後將它們恢復為用戶設置的值。
我怎麽能輕易做到這一點?
我是否有辦法簡單地將:set
(或類似命令)的結果存儲到我可以獲取的變量中,或者稍後傳遞給另一個命令以恢復它包含的內容?
或者我是否必須手動解析命令的輸出(我可以這樣做,但如果存在更簡單的替代方案,則無需任何工作)?
You can access a setting's value using let option_val =
&option
in a script. What I've seen done is using a dict
to store the options that you want to change. You iterate over the
dict to store the old value and set the new.
這是一種更直接的方法。如果提前知道設置,我會使用它。
function! s:do_something() abort
" Options needed by the plugin
let plugin_options = {
\ 'list': 0,
\ 'winfixwidth': 1,
\ 'autoindent': 0,
\ 'filetype': 'ini',
\ }
echo 'desired:' plugin_options
for option in keys(plugin_options)
execute 'let old_val = &'.option
execute 'let &'.option.' = plugin_options[option]'
let plugin_options[option] = old_val
endfor
echo 'changed:' plugin_options
for option in keys(plugin_options)
execute 'let &'.option.' = plugin_options[option]'
endfor
endfunction
call s:do_something()
plugin_options
變量的作用域是函數,因此可以重用它來存儲舊的選項值。
The script below will allow you to change the settings anywhere
within your script while maintaining the original settings until
you call s:restore_settings()
function! s:set(option, value) abort
if !exists('b:_saved_settings')
let b:_saved_settings = {}
endif
" Only save the original values
if !has_key(b:_saved_settings, a:option)
execute 'let b:_saved_settings[a:option] = &'.a:option
endif
execute 'let &'.a:option.' = a:value'
endfunction
function! s:restore_settings(...) abort
if !exists('b:_saved_settings')
return
endif
if a:0
for option in a:000
if has_key(b:_saved_settings, option)
execute 'let &'.option.' = b:_saved_settings[option]'
call remove(b:_saved_settings, option)
endif
endfor
else
for option in keys(b:_saved_settings)
execute 'let &'.option.' = b:_saved_settings[option]'
endfor
unlet! b:_saved_settings
endif
endfunction
" Options needed by the plugin
call s:set('list', 0)
call s:set('winfixwidth', 1)
call s:set('autoindent', 0)
call s:set('filetype', 'ini')
echo 'original:' b:_saved_settings
call s:restore_settings('list', 'filetype')
echo 'partial restore:' b:_saved_settings
call s:restore_settings()
s:set()
is somewhat similar to set
. It
will save the original setting's value if it hasn't been saved yet,
then use your setting's value.
不帶參數調用
s:restore_settings()
將完全恢復您的更改。有了參數,它將部分恢復它們。如果您決定使用它,那麽在最初調用
s:set()
之前調用
s:restore_settings()
是值得的,以防腳本先前在恢復之前遇到錯誤。