aboutsummaryrefslogtreecommitdiff
path: root/neovim/.config/nvim/lua/dyamon/session.lua
blob: ded51b4792216215c32ff755446f2886828de10d (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
--- Personal lua config files for NeoVim.
--  Last Changed: 2019-01-27
--  Author: Federico Igne <git@federicoigne.com>
--  License: This file is placed in the public domain.

local session = {}

-- Used as a dummy session file, when vim-obsession is loaded but the
-- current tab is not being tracked.
session.dummy = vim.env.NVIM_SESSIONS .. '/dummy.vim'

--- Get session name for current tab.
--
-- @param[opt=false] escaped whether to escape the file name or not
-- @return full path to session file
function session.name(escaped)
  local escaped = escaped or false
  local name = vim.fn.getcwd(-1,0):gsub('/','%%') .. ".vim"
  local path = vim.env.NVIM_SESSIONS .. '/'
  if escaped then
    path = path .. vim.fn.fnameescape(name)
  else
    path = path .. name
  end
  return path
end

--- Check if the session file (current tab) exists and it's readable.
function session.exists()
  return vim.fn.filereadable(session.name()) ~= 0
end

--- Create a new or load an existing session file.
--
-- This is essentially a wrapper around vim-obsession to make it
-- tab-aware. Starts tracking a new session if none exists for the
-- current tab.
function session.load()
  local cmd = 'mksession!'
  if session.exists() then
      cmd = 'source'
  elseif vim.fn.exists(':Obsession') then
      cmd = 'Obsession'
  end
  vim.t.this_session = session.name()
  vim.api.nvim_command(cmd .. ' ' .. session.name(true))
end

--- Prompt to switch session on a `DirChanged` event.
--
-- When using `:tcd` to switch working directory prompt the user to
-- switch session (creating a new one if necessary).
function session.changed(event)
  if not event.changed_window and
     event.scope == 'tab' and
     vim.t.this_session ~= session.name()
  then
    local action = "Create"
    if session.exists() then action = "Load" end
    if vim.fn.input(action .. " session for the current project? [yN]: ") == 'y' then
      session.load()
    end
  end
end

--- Helper function triggered by `ObsessionPre`
--
-- Save custom tab names in session
function session.pre()
  if vim.t.tablabel then
      vim.g.obsession_append = { 'let t:tablabel = "' .. vim.t.tablabel .. '"' }
  end
end

return session