nVim/lua/core/autocommands.lua
Robert Morrison 0d623139fa fix: Make colorcolumn work properly
Setting `colorcolumn` as a window option breaks any window
that does not need it set.
Use an autocmd to fix this.
2026-04-09 20:25:43 +01:00

60 lines
1.8 KiB
Lua

-- Control cursorline option
-- This function allows the easy creation of autocommands that configure cursorline for one buffer
-- either based on events or filetypes
local auGroupCursorLine = vim.api.nvim_create_augroup("CursorLine",
{ clear = true })
local set_cursorline = function(event, value, pattern)
vim.api.nvim_create_autocmd(event, {
group = auGroupCursorLine,
pattern = pattern,
callback = function()
vim.opt_local.cursorline = value
end,
})
end
set_cursorline("WinLeave", false)
set_cursorline("WinEnter", true)
set_cursorline("FileType", false, "TelescopePrompt")
-- Wrangle formatoptions
-- Format options is local to the buffer
-- This autocommand fixes formatoptions for all buffers at load
local auGroupFormatOptions = vim.api.nvim_create_augroup("FormatOptions",
{ clear = true })
vim.api.nvim_create_autocmd("FileType", {
group = auGroupFormatOptions,
pattern = "*",
callback = function()
vim.opt.formatoptions = vim.opt.formatoptions -- take the default
- "r" -- remove auto commenting
- "o" -- and for newlines
end,
})
-- Do some magic for colorcolumn
-- if set as a window option for a file, anything that uses that window
-- at a later date will inherit that even if it doesn't make sense.
local auGroupColorColumn = vim.api.nvim_create_augroup("ColorColumn",
{clear=true})
vim.api.nvim_create_autocmd( 'BufEnter', {
group = auGroupColorColumn,
pattern = "*",
callback = function (_)
-- if we set textwidth we show a colorcolumn
if vim.bo.textwidth > 0 then
local warn=vim.bo.textwidth - 5
vim.wo.colorcolumn=string.format("%d,%d", warn, vim.bo.textwidth)
else
vim.wo.colorcolumn=""
end
end,
}
)
vim.api.nvim_create_autocmd('BufLeave',{
group=auGroupColorColumn,
pattern = '*',
callback = function ()
vim.wo.colorcolumn=""
end
})