" 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
  " - neovim is opened with nvim -q
  if (argc(-1) > 0 || fugitive#Head() == '' || g:session_in_pager_mode == 1 || (!empty(getqflist())))
    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()
