How to open file in vim while having session autoload?

久未见 提交于 2019-12-13 02:47:48

问题


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.

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.


回答1:


Should be something like this:

" 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


来源:https://stackoverflow.com/questions/56324295/how-to-open-file-in-vim-while-having-session-autoload

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!