Add nvim autocmds: trim whitespace, restore cursor, yank highlight

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
kappa
2026-02-09 11:29:54 +09:00
parent 559a140780
commit 5ea9da14ca

View File

@@ -1,8 +1,52 @@
-- Autocmds are automatically loaded on the VeryLazy event
-- Default autocmds that are always set: https://github.com/LazyVim/LazyVim/blob/main/lua/lazyvim/config/autocmds.lua
--
-- Add any additional autocmds here
-- with `vim.api.nvim_create_autocmd`
--
-- Or remove existing autocmds by their group name (which is prefixed with `lazyvim_` for the defaults)
-- e.g. vim.api.nvim_del_augroup_by_name("lazyvim_wrap_spell")
local autocmd = vim.api.nvim_create_autocmd
local augroup = vim.api.nvim_create_augroup
-- Remove trailing whitespace on save
autocmd("BufWritePre", {
group = augroup("trailing_whitespace", { clear = true }),
pattern = "*",
callback = function()
local pos = vim.api.nvim_win_get_cursor(0)
vim.cmd([[%s/\s\+$//e]])
vim.api.nvim_win_set_cursor(0, pos)
end,
})
-- Restore last cursor position
autocmd("BufReadPost", {
group = augroup("restore_cursor", { clear = true }),
callback = function()
local mark = vim.api.nvim_buf_get_mark(0, '"')
local lines = vim.api.nvim_buf_line_count(0)
if mark[1] > 0 and mark[1] <= lines then
pcall(vim.api.nvim_win_set_cursor, 0, mark)
end
end,
})
-- Highlight on yank
autocmd("TextYankPost", {
group = augroup("highlight_yank", { clear = true }),
callback = function()
vim.highlight.on_yank({ timeout = 200 })
end,
})
-- Auto-resize splits on window resize
autocmd("VimResized", {
group = augroup("resize_splits", { clear = true }),
command = "tabdo wincmd =",
})
-- Close some filetypes with q
autocmd("FileType", {
group = augroup("close_with_q", { clear = true }),
pattern = { "help", "man", "qf", "checkhealth", "lspinfo", "startuptime" },
callback = function(event)
vim.bo[event.buf].buflisted = false
vim.keymap.set("n", "q", "<cmd>close<cr>", { buffer = event.buf, silent = true })
end,
})