Files
nvim-config/lua/config/autocmds.lua
2026-01-12 23:12:11 -07:00

109 lines
2.6 KiB
Lua

-- Autocommands
local augroup = vim.api.nvim_create_augroup
local autocmd = vim.api.nvim_create_autocmd
-- Highlight on yank
augroup("YankHighlight", { clear = true })
autocmd("TextYankPost", {
group = "YankHighlight",
callback = function()
vim.highlight.on_yank({ higroup = "IncSearch", timeout = 200 })
end,
})
-- Resize splits when window is resized
augroup("ResizeSplits", { clear = true })
autocmd("VimResized", {
group = "ResizeSplits",
callback = function()
vim.cmd("tabdo wincmd =")
end,
})
-- Go to last location when opening a buffer
augroup("LastLocation", { clear = true })
autocmd("BufReadPost", {
group = "LastLocation",
callback = function(event)
local exclude = { "gitcommit" }
local buf = event.buf
if vim.tbl_contains(exclude, vim.bo[buf].filetype) or vim.b[buf].lazyvim_last_loc then
return
end
vim.b[buf].lazyvim_last_loc = true
local mark = vim.api.nvim_buf_get_mark(buf, '"')
local lcount = vim.api.nvim_buf_line_count(buf)
if mark[1] > 0 and mark[1] <= lcount then
pcall(vim.api.nvim_win_set_cursor, 0, mark)
end
end,
})
-- Close certain filetypes with q
augroup("CloseWithQ", { clear = true })
autocmd("FileType", {
group = "CloseWithQ",
pattern = {
"help",
"lspinfo",
"man",
"notify",
"qf",
"spectre_panel",
"startuptime",
"checkhealth",
},
callback = function(event)
vim.bo[event.buf].buflisted = false
vim.keymap.set("n", "q", "<cmd>close<cr>", { buffer = event.buf, silent = true })
end,
})
-- Auto create parent directories when saving
augroup("AutoCreateDir", { clear = true })
autocmd("BufWritePre", {
group = "AutoCreateDir",
callback = function(event)
if event.match:match("^%w%w+://") then
return
end
local file = vim.uv.fs_realpath(event.match) or event.match
vim.fn.mkdir(vim.fn.fnamemodify(file, ":p:h"), "p")
end,
})
-- Set specific options for certain filetypes
augroup("FileTypeSettings", { clear = true })
-- Go files: use tabs
autocmd("FileType", {
group = "FileTypeSettings",
pattern = "go",
callback = function()
vim.opt_local.expandtab = false
vim.opt_local.tabstop = 4
vim.opt_local.shiftwidth = 4
end,
})
-- Makefile: use tabs
autocmd("FileType", {
group = "FileTypeSettings",
pattern = "make",
callback = function()
vim.opt_local.expandtab = false
vim.opt_local.tabstop = 4
vim.opt_local.shiftwidth = 4
end,
})
-- Markdown: enable wrap
autocmd("FileType", {
group = "FileTypeSettings",
pattern = "markdown",
callback = function()
vim.opt_local.wrap = true
vim.opt_local.spell = true
end,
})