Skip to main content
The lua/user/autocommands.lua file defines autocommands that automatically execute actions in response to specific events in Neovim.

Overview

Autocommands (autocmds) allow you to automatically trigger commands when certain events occur, such as opening a file, changing buffers, or resizing windows.

Configuration Structure

All autocommands are defined using Vim script wrapped in Lua:
lua/user/autocommands.lua
vim.cmd [[
  augroup group_name
    autocmd!
    autocmd Event pattern command
  augroup end
]]
autocmd! clears all previous autocommands in the group, preventing duplicates when sourcing the file multiple times.

General Settings

Quick Close Windows

augroup _general_settings
  autocmd!
  autocmd FileType qf,help,man,lspinfo nnoremap <silent> <buffer> q :close<CR>
Event: FileTypePattern: qf,help,man,lspinfoAction: Map q to close the windowPurpose: Allows quick closing of special windows (quickfix list, help, man pages, LSP info) by pressing q.The <buffer> option ensures the mapping only applies to that specific buffer type.

Yank Highlighting

autocmd TextYankPost * silent!lua require('vim.highlight').on_yank({higroup = 'Visual', timeout = 200})

Visual Feedback

Event: TextYankPostPattern: * (all files)Action: Briefly highlight yanked (copied) textPurpose: Provides visual feedback when you yank text, making it clear what was copied.
  • Uses the Visual highlight group
  • Highlight lasts 200 milliseconds

Format Options

autocmd BufWinEnter * :set formatoptions-=cro
This prevents Neovim from automatically inserting comment leaders when you press Enter or o/O in normal mode.
Event: BufWinEnter Pattern: * (all files) Action: Remove c, r, and o from format options What it does:
  • c: Don’t auto-wrap comments using textwidth
  • r: Don’t insert comment leader after pressing Enter in insert mode
  • o: Don’t insert comment leader after pressing o or O in normal mode

Quickfix List Settings

autocmd FileType qf set nobuflisted
Prevents the quickfix list from appearing in the buffer list, keeping your buffer navigation cleaner.

Git Settings

augroup _git
  autocmd!
  autocmd FileType gitcommit setlocal wrap
  autocmd FileType gitcommit setlocal spell
augroup end
Event: FileType gitcommitAction: setlocal wrapPurpose: Enables line wrapping in git commit messages, making it easier to write longer commit descriptions.The local in setlocal means this only affects git commit buffers.
Event: FileType gitcommitAction: setlocal spellPurpose: Enables spell checking for git commit messages to catch typos.Misspelled words will be underlined. Use z= on a misspelled word to see suggestions.

Markdown Settings

augroup _markdown
  autocmd!
  autocmd FileType markdown setlocal wrap
  autocmd FileType markdown setlocal spell
augroup end

Enable Wrapping

Makes long lines in Markdown files wrap to the next line for better readability.

Enable Spell Check

Automatically enables spell checking for Markdown documents.
File Type: markdown Settings:
  • Line wrapping for long paragraphs
  • Spell checking for writing quality
Same behavior as git commits, but for Markdown files (.md).

Window Resize

augroup _auto_resize
  autocmd!
  autocmd VimResized * tabdo wincmd =
augroup end
This autocommand ensures all windows stay proportional when you resize your terminal.
Event: VimResized Pattern: * (all situations) Action: Equalize all window sizes How it works:
  • tabdo: Execute the following command in all tabs
  • wincmd =: Equalize the size of all windows
Purpose: When you resize your terminal or GUI, all split windows automatically adjust to equal sizes.

Alpha Dashboard Settings

augroup _alpha
  autocmd!
  autocmd User AlphaReady set showtabline=0 | autocmd BufUnload <buffer> set showtabline=2
augroup end
Event: User AlphaReadyAction: Hide the tab line when Alpha dashboard is shownCleanup: Restore tab line when leaving the dashboardPurpose: Provides a cleaner look for the startup dashboard by hiding the tab line, then restoring it when you open a file.
  • showtabline=0: Hide tab line
  • showtabline=2: Always show tab line

Commented Autoformat

-- Autoformat
-- augroup _lsp
--   autocmd!
--   autocmd BufWritePre * lua vim.lsp.buf.formatting()
-- augroup end
This autocommand is commented out by default. Uncomment it to enable automatic code formatting on save.
When enabled:
  • Event: BufWritePre (before saving)
  • Action: Format the buffer using LSP
  • Pattern: * (all files)
To enable:
  1. Remove the comment markers (--)
  2. Save and reload the configuration
  3. Code will auto-format whenever you save a file
Note: Requires LSP to be properly configured for the file type.

Creating Custom Autocommands

1

Choose the event

Determine what event should trigger your autocommand.Common events:
  • BufRead, BufNewFile: When opening files
  • BufWritePre, BufWritePost: Before/after saving
  • FileType: When file type is detected
  • InsertEnter, InsertLeave: Entering/leaving insert mode
2

Create an augroup

Group related autocommands together:
vim.cmd [[
  augroup _my_custom_group
    autocmd!
    -- your autocommands here
  augroup end
]]
3

Add your autocommand

Define the pattern and action:
autocmd FileType python setlocal tabstop=4 shiftwidth=4
4

Test and reload

Save the file and test your autocommand by triggering the event.

Example Custom Autocommands

-- Save automatically when leaving insert mode
augroup _auto_save
  autocmd!
  autocmd InsertLeave * silent! write
augroup end

Common Autocommand Events

EventDescription
BufNewFileStarting to edit a file that doesn’t exist
BufRead, BufReadPostAfter reading a file
BufWrite, BufWritePreBefore/during writing a file
BufEnterAfter entering a buffer
BufLeaveBefore leaving a buffer
FileTypeWhen file type is set
InsertEnterStarting insert mode
InsertLeaveLeaving insert mode
TextChangedAfter a change was made in normal mode
TextChangedIAfter a change was made in insert mode
VimResizedAfter Vim window was resized
CursorHoldCursor hasn’t moved for updatetime ms

Lua-Style Autocommands

You can also define autocommands using Neovim’s Lua API instead of Vim script.
local augroup = vim.api.nvim_create_augroup
local autocmd = vim.api.nvim_create_autocmd

-- Create augroup
local general = augroup("_general_settings", { clear = true })

-- Create autocommand
autocmd("TextYankPost", {
  group = general,
  pattern = "*",
  callback = function()
    vim.highlight.on_yank({ higroup = "Visual", timeout = 200 })
  end,
})
This is the modern Lua approach and offers better integration with Lua functions.

Best Practices

Use Augroups

Always wrap autocommands in augroups with autocmd! to prevent duplicates.

Be Specific

Use specific patterns instead of * when possible to avoid unnecessary triggers.

Test Carefully

Some autocommands can impact performance if they run too frequently.

Use Silent

Add silent! to suppress error messages for non-critical commands.

See Also

Options

Configure editor settings and behavior

Keymaps

Set up custom key bindings

Build docs developers (and LLMs) love