-- highlight when yanking text
Autocmd('TextYankPost', {
	desc = 'highlight when yanking text',
	group = vim.api.nvim_create_augroup('kickstart-highlight-yank', { clear = true }),
	callback = function()
		vim.highlight.on_yank()
	end,
})

-- disable new line comment
Autocmd("BufEnter", {
	desc = "disable bew line comment",
	callback = function()
		vim.opt.formatoptions:remove({ "c", "r", "o" })
	end,
})

-- go to last location when opening a buffer
Autocmd("BufReadPost", {
	desc = "go to last location when opening a buffer",
	callback = function()
		local mark = vim.api.nvim_buf_get_mark(0, '"')
		local lcount = vim.api.nvim_buf_line_count(0)
		if mark[1] > 0 and mark[1] <= lcount then
			pcall(vim.api.nvim_win_set_cursor, 0, mark)
		end
	end,
})

-- close certain windows with q
Autocmd('FileType', {
	desc = 'close certain windows with q',
	pattern = { 'help', 'man', 'qf', 'query', 'messages', 'netrw' },
	callback = function(evt)
		vim.bo[evt.buf].buflisted = false
		Map('n', 'q', '<cmd>close<cr>')
	end
})

-- disable spellcheck in terminal
Autocmd('TermOpen', {
	callback = function()
		vim.opt.spell = false
	end,
})

-- closes the first buffer if it is empty
Autocmd('BufEnter', {
	pattern = '*',
	callback = function()
		local bufs = vim.api.nvim_list_bufs()

		-- check if the first buffer is an empty one
		if #bufs == 0 and vim.api.nvim_get_option_value('buftype', { buf = bufs[1] }) and vim.api.nvim_buf_get_name(bufs[1]) then
			vim.api.nvim_buf_delete(bufs[1], {})
		end
	end,
})

---@type table<string, string>
local filemap = {
	['*.h'] = 'c',
	['*/i3/**.conf'] = 'i3config'
}

for pat, file in pairs(filemap) do
	Autocmd('BufRead', {
		pattern = pat,
		callback = function()
			vim.bo.filetype = file
		end
	})
end
