summaryrefslogtreecommitdiffstats
path: root/lua/inbox/init.lua
blob: bb59fc42bc1eea8e19105fd5eb40ffc554ad696a (plain)
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
local M = {
	buffers = {},
}

function M.select()
	local mode = vim.api.nvim_get_mode().mode
	local is_visual = mode:match("^[vV]")

	local entries = {}
	if is_visual then
		-- This is the best way to get the visual selection at the moment
		-- https://github.com/neovim/neovim/pull/13896
		local _, start_lnum, _, _ = unpack(vim.fn.getpos("v"))
		local _, end_lnum, _, _, _ = unpack(vim.fn.getcurpos())
		if start_lnum > end_lnum then
			start_lnum, end_lnum = end_lnum, start_lnum
		end
		for i = start_lnum, end_lnum do
			local entry = M.get_entry_on_line(0, i)
			if entry then
				table.insert(entries, entry)
			end
		end
	else
		local entry = M.get_cursor_entry()
		if entry then
			table.insert(entries, entry)
		end
	end
end

function M.open(maildir)
	local view = require("inbox.view")
	if M.bufnr == nil then
		M.bufnr = view.initialize(maildir)
	end

	if not vim.api.nvim_buf_is_valid(M.bufnr) then
		--- TODO: Handle error
		return
	end

	vim.api.nvim_set_current_buf(M.bufnr)
end

function M.open_entry(part)
	local view = require("inbox.view")

	local lnum = vim.api.nvim_win_get_cursor(0)[1]
	local id = vim.b[0].inbox_ids[lnum]

	if id == nil then
		vim.notify("Failed to get entry under cursor", vim.log.levels.ERROR)
		return nil
	end

	local bufnr = view.render_entry(id, part)

	if bufnr ~= nil then
		vim.api.nvim_set_current_buf(bufnr)
	end
end

function M.open_part()
	local indexers = require("inbox.indexers")
	local indexer = indexers.get_indexer()
	local lnum = vim.api.nvim_win_get_cursor(0)[1]
	local id = vim.b[0].inbox_ids[lnum]

  -- FIX: fails to open selected part.
	local parts = indexer.get_entry(id).parts
	if vim.tbl_isempty(parts) then
		vim.notify(("Failed to get parts for entry id: %s"):format(id), vim.log.levels.ERROR)
		return nil
	end

	vim.ui.select(parts, {}, M.open_entry)
end

---@param opts inbox.Config
function M.setup(opts)
	local config = require("inbox.config")
	local indexers = require("inbox.indexers")
	local utils = require("inbox.utils")

	config.setup(opts)
	indexers.setup(config.indexer_config)

	for sign, value in pairs(config.flags) do
		local name = utils.sign_name(sign)
		vim.fn.sign_define(name, value)
	end
end

return M