nvim: plugin: Add a simple session management plugin

This commit is contained in:
Sanchayan Maity 2023-05-01 11:40:05 +05:30
parent 7271c9b030
commit eafc975e35
Signed by: sanchayanmaity
GPG Key ID: 6F6A0609C12038F3
1 changed files with 66 additions and 0 deletions

View File

@ -0,0 +1,66 @@
" Session management which does exactly what we want. No Telescope non-sense.
" Saves session with a fixed name to a fixed path. We do not allow creating
" sessions in non Git repositories. Automatically loads a session if one is
" available for the current directory. Exposes SessionSave command for creating
" a session.
let g:session_in_pager_mode = 0
let g:session_loaded = 0
function! s:SessionFile()
let session_name = join(split(getcwd(), '/'), '\%') . ".vim"
let session_path = expand('~/.vim/session/')
let session_file = session_path . '\%'. session_name
return session_file
endfunction
function! s:SessionCreate()
if (fugitive#Head() == '')
echo "Will not create session in a non Git repository"
return
endif
let session_file = s:SessionFile()
silent execute ':mksession! ' . session_file
endfunction
function! s:SessionLoad()
" Do not load session if
" - neovim is started with arguments
" - neovim is opened outside a git repository
" - neovim is in pager mode and is getting input from STDIN
if (argc(-1) > 0 || fugitive#Head() == '' || g:session_in_pager_mode == 1)
return
endif
let session_file = s:SessionFile()
if (!empty(glob(session_file)))
silent execute ':source' . session_file
" We noticed a case where session was loaded, so argc() had to be 0
" but after session load, argc() returned 1. Use a global variable to
" track if session was loaded. The save path will check this and save
" only if a session was loaded in the first place.
let g:session_loaded = 1
endif
endfunction
function! s:SessionSave()
" Do not save a session which was not loaded in the first place.
if (g:session_loaded == 1)
let session_file = s:SessionFile()
silent execute ':mksession! ' . session_file
endif
endfunction
augroup Session
autocmd!
autocmd VimEnter * nested call s:SessionLoad()
autocmd VimLeavePre * call s:SessionSave()
augroup END
augroup StdIn
autocmd!
autocmd StdinReadPre * let g:session_in_pager_mode = 1
augroup END
command SessionSave :call s:SessionCreate()