summaryrefslogtreecommitdiff
path: root/lua/windownav.lua
blob: 9ac83e3df6ba00461b4e11f89c6520572c9471a4 (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
76
local vim = assert(vim)
local augroup = vim.api.nvim_create_augroup   -- Create/get autocommand group
local autocmd = vim.api.nvim_create_autocmd   -- Create autocommand

M = {}

local function get_buffers(options)
    local buffers = {}
    local len = 0
    local options_listed = options.listed
    local vim_fn = vim.fn
    local buflisted = vim_fn.buflisted

    for buffer = 1, vim_fn.bufnr('$') do
        if not options_listed or buflisted(buffer) ~= 1 then
            len = len + 1
            buffers[len] = buffer
        end
    end

    return buffers
end

function M.goto_terminal()
  for _, buf in pairs(vim.fn.tabpagebuflist()) do
    if string.match(vim.fn.bufname(buf), "^term://.*") then
      local win = vim.fn.bufwinnr(buf)
      vim.api.nvim_exec(win .. "wincmd w", 0)
      return
    end
  end
end

local function contains(needle, haystack)
  for _, h in pairs(haystack) do
    if h == needle then
      return true
    end
  end
  return false
end

local function navigate_to(buffer)
  local wid = vim.fn.win_findbuf(buffer)
  if #wid > 0 then
    vim.fn.win_gotoid(wid[1])
  end
end

function M.goto_lastwin()
  if M.lastwin then
    vim.fn.win_gotoid(M.lastwin)
  end
end

function M.goto_initvim()
  local buffers = get_buffers({})
  for _, buf in pairs(buffers) do
    if string.match(vim.fn.bufname(buf), "nvim/init.vim$") then
      navigate_to(buf)
      return
    end
  end

  vim.api.nvim_exec("tabedit ~/.config/nvim/init.vim", 0)
end

augroup('WindowNav', { clear = true })
autocmd('WinLeave', {
  group = 'WindowNav',
  callback = function ()
    M.lastwin = vim.fn.win_getid()
  end
})

return M