会话自动加载时如何在vim中打开文件? [英] How to open file in vim while having session autoload?

查看:98
本文介绍了会话自动加载时如何在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

这篇关于会话自动加载时如何在vim中打开文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆