会话自动加载时如何在vim中打开文件?
.vimrc中有以下代码可在vim启动时自动保存/加载会话:
I have following code in .vimrc to automatically save / load session on vim start:
" Session saving
" Automatically save / rewrite the session when leaving Vim
augroup leave
autocmd VimLeave * mksession! ~/.vim/session.vim
augroup END
" Automatically silently load the session when entering vim
autocmd VimEnter * silent source ~/.vim/session.vim
哪个可以正常工作,我唯一的问题是当我想创建新文件或使用以下命令打开现有文件时:
Which works properly, the only issue I have is when I want to create new file or open existing with:
vim test.txt
在这种情况下,不会打开文件,而是加载了上次保存的会话.
In this case file is not opened and instead I have the last saved session loaded.
以下是所需的行为.当我不带任何参数运行vim
时,它将恢复上一个会话.如果我提供文件参数,则为e.x. vim test.py
-加载上一个会话,并在新选项卡中打开/创建提供的文件.
怎么做?理想情况下,没有任何插件.
The desired behavior is following. When I run vim
with no arguments - it restores last session. If I provide file argument, e.x. vim test.py
- it loads last session AND in new tab opens / creates provided file.
How to do it? Ideally without any plugins.
应该是这样的:
" use ++nested to allow automatic file type detection and such
autocmd VimEnter * ++nested call <SID>load_session()
function! s:load_session()
" save curdir and arglist for later
let l:cwd = getcwd()
let l:args = argv()
" source session
silent source ~/.vim/session.vim
"restore curdir (otherwise relative paths may change)
call chdir(l:cwd)
" open all args
for l:file in l:args
execute 'tabnew' l:file
endfor
" add args to our arglist just in case
execute 'argadd' join(l:args)
endfunction